Let's say I have a DIV containing text, like so:
<div>
Hello world
test
Hello world
test 2
Hello world
</div>
My function for getting the word when selecting the text is:
function getWord() {
var txt = document.getSelection();
var txtRange = txt.getRangeAt(0);
return txtRange;
}
Let's say I select the middle "Hello world", which is the 2nd occurrence. How do I get the occurrence, which in this case would be 2?
I have the solution:
function getWord() {
var txt = document.getSelection();
var txtRange = txt.getRangeAt(0);
return txtRange;
}
var t = getWord();
var text = document.getElementsByClassName("content")[0];
var precedingRange = document.createRange();
precedingRange.setStartBefore(text.firstChild);
precedingRange.setEnd(t.startContainer, t.startOffset);
var textPrecedingSelection = precedingRange.toString();
var count = (textPrecedingSelection.match(new RegExp(t.toString().trim(), 'gi')) || []).length + 1;
alert("Word occurrence: " + count);