Javascript, action on selected text


Galera would like to know how to do an action on text selected in 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 looking all day and I do not think so. Thank you for your attention.

asked by anonymous 20.08.2015 / 21:11

2 answers


You can use the selectionStart and selectionEnd attributes of textarea to determine which part of it is selected. So just replace this snippet with its value ( value ).

Example (takes the value to the beginning of the selection, together with the string to insert, 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" +
<textarea>oi, tudo bem?</textarea>
20.08.2015 / 21:25

Here is 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>
<button id="botao" onclick="selecionaTexto();">Trocar</button>
20.08.2015 / 21:34