JavaScript get word before cursor

前端 未结 3 1567
我寻月下人不归
我寻月下人不归 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 01:52

    With using Caret Position finder method provided here this will do what you want.

    function ReturnWord(text, caretPos) {
        var index = text.indexOf(caretPos);
        var preText = text.substring(0, caretPos);
        if (preText.indexOf(" ") > 0) {
            var words = preText.split(" ");
            return words[words.length - 1]; //return last word
        }
        else {
            return preText;
        }
    }
    
    function AlertPrevWord() {
        var text = document.getElementById("textArea");
        var caretPos = GetCaretPosition(text)
        var word = ReturnWord(text.value, caretPos);
        if (word != null) {
            alert(word);
        }
    
    }
    
    function GetCaretPosition(ctrl) {
        var CaretPos = 0;   // IE Support
        if (document.selection) {
            ctrl.focus();
            var Sel = document.selection.createRange();
            Sel.moveStart('character', -ctrl.value.length);
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (ctrl.selectionStart || ctrl.selectionStart == '0')
            CaretPos = ctrl.selectionStart;
        return (CaretPos);
    }
    <input id="textArea" type="text" />
    <br />
    <input id="Submit" type="submit" value="Test" onclick="AlertPrevWord()" />

    Here is also a jsfiddle.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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 '';
        }
    }
    
    0 讨论(0)
提交回复
热议问题