Quan
Quan

Reputation: 27

How to select a word or a phrase in a text area in JavaScript?

I am currently creating a text editor in HTML and JavaScript and I want to add a find function where you would type the word that you want to find then it will select the word. Now what I mean by "select" here is that the script will select with the blue color around a word so that I could copy, cut, paste, delete. Because I can't find a solution on the Internet, is there a way to do the thing I talk earlier in pure JavaScript?

Example: The Find Function

Upvotes: 0

Views: 1618

Answers (1)

mplungjan
mplungjan

Reputation: 177685

Rewrite of How to select line of text in textarea

http://jsfiddle.net/mplungjan/jc7fvt0b/

Change the select to an input field to type yourself

function selectTextareaWord(tarea, word) {
  const words = tarea.value.split(" ");

  // calculate start/end
  const startPos = tarea.value.indexOf(word),
    endPos = startPos + word.length

  if (typeof(tarea.selectionStart) != "undefined") {
    tarea.focus();
    tarea.selectionStart = startPos;
    tarea.selectionEnd = endPos;
    return true;
  }

  // IE
  if (document.selection && document.selection.createRange) {
    tarea.focus();
    tarea.select();
    var range = document.selection.createRange();
    range.collapse(true);
    range.moveEnd("character", endPos);
    range.moveStart("character", startPos);
    range.select();
    return true;
  }

  return false;
}

/// debugging code
var sel = document.getElementById('wordSelector');
var tarea = document.getElementById('tarea');
sel.onchange = function() {
  selectTextareaWord(tarea, this.value);
}
<select id='wordSelector'>
  <option>- Select word -</option>
  <option>first</option>
  <option>second</option>
  <option>third</option>
  <option>fourth</option>
  <option>fifth</option>
</select><br/>
<textarea id='tarea' cols='40' rows='5'>first second third fourth fifth</textarea>

Upvotes: 4

Related Questions