如何在JavaScript的文本区域中选择单词或短语?

问题描述

我目前正在使用HTML和JavaScript创建一个文本编辑器,并且我想添加一个find函数,您可以在其中键入要查找的单词,然后它将选择该单词。现在,我在这里所说的“选择”是指脚本将使用单词周围的蓝色进行选择,以便我可以复制,剪切,粘贴,删除。因为我无法在Internet上找到解决方案,所以有什么方法可以用纯JavaScript来完成我之前所说的事情?

示例:

The Find Function

解决方法

重写How to select line of text in textarea

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

将选择更改为输入字段以输入自己的名字

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>