Javascript, action on a selected text

Asked

Viewed 2,503 times

8

People would like to know how to do an action on a selected text in the textarea, for example I selected the word 'hi' and when I click a button with Onlick, change the text to 'bye''.

I await the answer, because I am all day looking and do not find. I thank you for your attention.

2 answers

9


You can use the attributes selectionStart and selectionEnd of textarea to determine which section of the same is selected. Then just replace this section in its value (value).

Example (takes the value until the beginning of the selection, joins with the string to be inserted, and closes with the value after the end of the selection):

document.querySelector("button").onclick = function() {
  var ta = document.querySelector("textarea");
  ta.value = ta.value.substring(0, ta.selectionStart) +
             "tchau" +
             ta.value.substring(ta.selectionEnd);
}
<textarea>oi, tudo bem?</textarea>
<button>Trocar</button>

  • Po guy saved me, you have no idea when I was looking for this, was doing test with the . select(), but nothing. Thank you very much.

3

There’s an example using pure javascript:

function selecionaTexto() {
  var textArea = document.getElementById('texto');
  var selectedText;

  if (textArea.selectionStart != undefined) { //Se tiver algo selecionado
    var startPos = textArea.selectionStart; //Inicio da selecao
    var endPos   = textArea.selectionEnd;     //Fim da selecao
    selectedText = textArea.value.substring(startPos, endPos);
    if (selectedText == "Oi") { //Se selecao foir "Oi"
      var novoTexto = textArea.value.substring(0, startPos) +
                      "Tchau" + textArea.value.substring(endPos);
      textArea.value = novoTexto;
    }
  }
}
<textarea id="texto">Oi senhor usuário</textarea>
</br>
<button id="botao" onclick="selecionaTexto();">Trocar</button>

  • Po Very Nice Show thank you for your attention. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.