0

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

Quan
  • 27
  • 2
  • 6
  • Does this answer your question? [Selecting text in an element (akin to highlighting with your mouse)](https://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse) – Wais Kamal Sep 08 '20 at 12:06
  • Does this answer your question? [Set keyboard caret position in html textbox](https://stackoverflow.com/questions/512528/set-keyboard-caret-position-in-html-textbox) – luk2302 Sep 08 '20 at 12:06

1 Answers1

3

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236