从文本中间捕获最后输入的单词

VGr*_*nin 1 html javascript jquery

我需要捕获用户在div/textarea中键入的最后一个单词.当这个词是最后一个词时,这不是问题.但是如果用户在段落里面(中间)输入了这个词呢?

现在我有这个代码:

<div contenteditable="true">Add text here</div>
<script>
    $("div").on("keyup", function(e){
      if (e.keyCode === 0 || e.keyCode === 32) {
        var words = $(this).text().trim().split(' '),
            lastWord = words[words.length - 1];
        console.log(lastWord);
        }
    });
</script>
Run Code Online (Sandbox Code Playgroud)

用户点击空格后,它会占用文本的最后一个字.

Jav*_*Rey 5

使用文本的子字符串直到光标位置,您可以使用该window.getSelection函数获得:

$("div").on("keyup", function(e){
  if (e.keyCode === 0 || e.keyCode === 32) {
    var selection = getSelection();
    var line = selection.getRangeAt(0).endContainer.nodeValue;
    var cursor = selection.focusOffset;
    var words = line.substring(0, cursor).trim().split(' ');
    var lastWord = words[words.length - 1];
    console.log(lastWord);
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true">
  Add text here
  <br/>
  Or do it in this line
</div>
Run Code Online (Sandbox Code Playgroud)