如何 select JavaScript 中文本区域中的单词或短语?

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

我目前正在 HTML 和 JavaScript 中创建一个文本编辑器,我想添加一个查找功能,您可以在其中键入要查找的词,然后它将 select 这个单词。现在,我在这里所说的“select”的意思是,脚本将 select 与一个词周围的蓝色,以便我可以复制、剪切、粘贴、删除。因为在网上找不到解决方法,有没有办法把我刚才讲的纯JavaScript?

示例:

重写 How to select line of text in textarea

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

将 select 更改为您自己输入的输入字段

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>