Skip to content Skip to sidebar Skip to footer

Append And Remove Characters Before And After Selection

How can I get the characters before AND after the selected text, and then remove them? Or rather, if the selected text is within the characters, remove the surrounding characters,

Solution 1:

I would suggest a different approach, using plain JS, see the comments in the snippet :

var newText;
const elem = document.querySelector('.input');

document.querySelector('.test').addEventListener('click', e => {
  // get the content of the divconst text = elem.innerHTML;

  // get the selection, in a string format, trim the white spacesconst selection = window.getSelection();
  const selectionContent = selection.toString().trim();

  // if there's a word selectedif (selectionContent) {
    const range = selection.getRangeAt(0)

    // selected lineconst line = range.startContainer.data;

    // indexes of the sectionconst startIndex = range.startOffset;
    const endIndex = range.endOffset;

    // check if the backticks are included in the selectionconst backticksIncluded = selectionContent.match(/\`.*?\`/g) ? true : false;

    // check if the selected word is wrapped with backticks    const hasBackticks = backticksIncluded || "`" + selectionContent + "`" === line.slice(startIndex - 1, endIndex + 1);

    // check if the selection has a space in the endconst space = selection.toString().endsWith(" ") ? " " : "";

    if (hasBackticks) {
      // if the selected text with backticks is found, // replace it with the original selection ( without backticks)const startContent = line.slice(0, startIndex - (backticksIncluded ? 0 : 1));
      const endContent = line.slice(endIndex + (backticksIncluded ? 0 : 1));

      const newWord = backticksIncluded ? selectionContent.slice(1, -1) : selectionContent

      newText = startContent + newWord + space + endContent;
    } else {
      // if it doesn't have backticks, // replace the selected text with the one having backticksconst startContent = line.slice(0, startIndex);
      const endContent = line.slice(endIndex);

      newText = startContent + "`" + selectionContent + "`" + space + endContent;
    }

    // set the new content to the div
    elem.innerHTML = elem.innerHTML.replace(line.trim(), newText);
  }
});
<buttonclass="test">format</button><divcontenteditable="true"class="input">hello `text` hello world</div>

Post a Comment for "Append And Remove Characters Before And After Selection"