Home > Enterprise >  Wrap tags [start] [end] around selected text in textarea with Javascript
Wrap tags [start] [end] around selected text in textarea with Javascript

Time:10-03

I have a textarea where users can input text. With a button, they should be able to wrap a selected text in this textarea with custom tags [start] [end].

<button onclick="addTags();">Add Tags to selected Text</button>

<textarea id="user-input" name="user-input" rows="4" cols="50"></textarea>

Example: If the text in the textarea is for example "1 2 3" and user marks "2" and clicks the button the result in the textarea should be "1 [start]2[end] 3".

I am trying no to get a piece of javascript to work, that will do this for me.

I played around with "window.getSelection()". So the question is: What is the right approach for my function?

function addTags() {
...
}

CodePudding user response:

Cut the text up: before the selection, the selection, after the selection. Then reassemble with tags.

document.getElementById("add-tag").onclick = () => {
  let txt = document.getElementById("user-input");
  const before = txt.value.substring(0, txt.selectionStart);
  const sel = txt.value.substring(txt.selectionStart, txt.selectionEnd);
  const after = txt.value.substring(txt.selectionEnd);
  txt.value = `${before}[start]${sel}[end]${after}`;
}; 
<button id="add-tag">Add Tags to selected Text</button>

<textarea id="user-input" name="user-input" rows="4" cols="50"></textarea>

TODO: Handle case where nothing is selected.-

  • Related