JavaScript get word before cursor

前端 未结 3 1569
我寻月下人不归
我寻月下人不归 2020-12-30 01:11

Okay, I\'ve been looking all over the web to find a solution but I couldn\'t find one, is there a way to get the word before the caret position in an editable div so a bit l

3条回答
  •  萌比男神i
    2020-12-30 01:56

    Here is a rough method using the Selection and Range objects.

    function getWord() {
        var range = window.getSelection().getRangeAt(0);
        if (range.collapsed) {
            text = range.startContainer.textContent.substring(0, range.startOffset+1);
            return text.split(/\b/g).pop();
        }
        return '';
    }
    

    You can see it in action here: http://jsfiddle.net/ggfFw/1/. This will not work in IE. If you need IE support look at the Rangy library.

提交回复
热议问题