JavaScript get word before cursor

前端 未结 3 1566
我寻月下人不归
我寻月下人不归 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条回答
  •  执念已碎
    2020-12-30 02:10

    I had something like that https://stackoverflow.com/a/9960262/986160 yet at some point it wasn't getting a selection in my Chrome browser. Based on my other answer here: https://stackoverflow.com/a/26728677/986160 - I changed it accordingly to be:

    function getLastWordBeforeCaret() {
        const containerEl = document.getElementById('element-id');
        let preceding = '';
        let sel;
        let range;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel && sel.rangeCount > 0) {
                range = sel.getRangeAt(0).cloneRange();
                range.collapse(true);
                range.setStart(containerEl, 0);
                preceding = range.toString();
            }
        }
        let queryMatch = preceding.match(/([^\s]+)$/i);
        if (queryMatch) {
            return queryMatch[1];
        } else {
            return '';
        }
    }
    

提交回复
热议问题