如何将光标移动到文本区域中的 next/previous 个单词?

How to move cursor to next/previous word in textarea?

如何使用 Javascript 将光标移动到文本区域中的下一个或上一个单词?我正在尝试在 HTML 文本区域中复制 Emacs 命令 "forward one word" 和 "back one word"。

我可以使用 rangyinputs 获得当前的 caret/cursor 位置,但我还不确定如何在不使用各种拆分的情况下有效地移动到下一个单词,这些拆分在很长的片段上可能会很慢文本。

请参阅此 fiddle. I used functions from jQuery Set Cursor Position in Text Area 以更改光标的位置。

function nextWord(input) {
    var words = input.value.split(" "),
        index = 0;
    for (var i in words) {
        var word = words[i];
        if (index+word.length >= input.selectionStart) {
            setCaretToPos(input, index+word.length+1);
            break;
        }
        index += word.length+1;
    }
}
function previousWord(input) {
    var words = input.value.split(" ").reverse(),
        index = input.value.length;
    for (var i in words) {
        var word = words[i];
        if (index+1 <= input.selectionStart) {
        setCaretToPos(input, index-word.length);
            break;
        }
        index -= word.length+1;
    }
}

我使用了 here and .selectRange() from here 中的 setCaretToTextEnd()。以下函数使用 Emacs 风格的插入符位置,比循环单词更有效。

function nextWord(input) {
  let currentCaretPosition = input.selectionStart;

  // -1 Because Emacs goes to end of next word.
  let nextWordPosition = input.value.indexOf(' ', currentCaretPosition) - 1;
  if (nextWordPosition < 0) {
    input.setCaretToTextEnd();
  } else {
    input.selectRange(nextWordPosition);
  }
}

function previousWord(input) {
  let currentCaretPosition = input.selectionStart;

  // +1 Because Emacs goes to start of previous word.
  let previousWordPosition = input.value.lastIndexOf(' ', currentCaretPosition) + 1;
  if (previousWordPosition < 0) {
    input.selectRange(0);
  } else {
    input.selectRange(previousWordPosition);
  }
}