Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 376
Keekz Avatar asked Jun 13 '19 05:06

Keekz


People also ask

What is getSelection in Javascript?

getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.

How do we know if the text in the document is selected or not?

<input type="button" onmousedown="alert(isTextSelected(document. getElementById('test')));" value="Selected?">


1 Answers

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>
like image 115
pawelbylina Avatar answered Oct 27 '22 22:10

pawelbylina