How to find index of selected text in getSelection() using javascript?

懵懂的女人 提交于 2021-02-07 03:03:23

问题


I am trying to apply style to the text selected by the user(mouse drag) for which I need to get the start and end index of the selected text.

I have tried using "indexOf(...)" method. but it returns the first occurrence of the selected substring. I want the actual position of the substring with respect to the original string. For example.., if I select the letter 'O' at position 3 [YOLO Cobe], I expect the index as 3 but the indexOf() method returns 1 which is the first occurrence of 'O' in [YOLO Cobe].

Is there any other method of getting the actual start and end index of selected text and not the first occurrence ?

function getSelectionText()
{
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    }
    return text;
}
document.getElementById('ip').addEventListener('mouseup',function(e)
{
        var txt=this.innerText;
        console.log(txt);
        var selectedText = getSelectionText();
        console.log(selectedText);
        var start = txt.indexOf(selectedText);
        var end = start + selectedText.length;
        if (start >= 0 && end >= 0){
    	    console.log("start: " + start);
    	    console.log("end: " + end);
        }
});
<div id="ip">YOLO Cobe</div>

回答1:


What you are looking for is available inside object returned by window.getSelection()

document.getElementById('ip').addEventListener('mouseup',function(e)
{
        var txt = this.innerText;
        var selection = window.getSelection();
        var start = selection.anchorOffset;
        var end = selection.focusOffset;
        if (start >= 0 && end >= 0){
    	    console.log("start: " + start);
    	    console.log("end: " + end);
        }
});
<div id="ip">YOLO Cobe</div>

And here is example for more complex selections on page based on @Kaiido comment:

document.addEventListener('mouseup',function(e)
{
        var txt = this.innerText;
        var selection = window.getSelection();
        var start = selection.anchorOffset;
        var end = selection.focusOffset;
        console.log('start at postion', start, 'in node', selection.anchorNode.wholeText)
        console.log('stop at position', end, 'in node', selection.focusNode.wholeText)
});
<div><span>Fragment1</span> fragment2 <span>fragment3</span></div>



回答2:


window.getSelection().anchorOffset will give you the index that you are looking for.

MDN link: https://developer.mozilla.org/en-US/docs/Web/API/Selection/anchorOffset



来源:https://stackoverflow.com/questions/56574059/how-to-find-index-of-selected-text-in-getselection-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!