I'm trying to get the start index and end index of user-highlighted text within a larger piece of text. On my site, users can write their own articles. When a user goes to read the article, the user can highlight any text of the article and a box will appear where they can post a comment about what they highlighted. I'm trying to get the start and end indices of the highlighted text within the larger article. For example, if the user had an "article" with the text:
<div class='article'>Hi there, everyone!</div>
and then a different user highlighted the text Hi there
, I would want to find what the start and end position are within that block of text. I originally tried setting these variables to get the start and end position like so:
startIndex = window.getSelection().getRangeAt(0).startOffset;
endIndex = window.getSelection().getRangeAt(0).endOffset;
which did give me the indices. But the problem is that once the user highlights one piece of text within the article, if I then highlight the word next to the word I just highlighted, the index restarts from 0, not from its "correct" position within the text. This is because when the user highlights any text and submits a comment, the text they highlighted is then underlined with the color blue by adding <span>
tags around the highlighted text. This addition of the span tag is what I believe makes the index start over again from 0. For example, if I highlight the text Hi there
in the original "article" text above, the start and end indices would be 0, 7
respectively. That text would then get a blue underline. If I then highlight the text everyone!
, the start and end indices would be 2, 10
respectively. However, the "true" start and end positions of the text everyone!
should be 10, 18
respectively because that's where the characters lie when disregarding the added span tag that underlines the highlighted text. Because of this, I believe I need to first get the contents of the article, like so:
var contents = $(".article").text();
and then find where index of the user-highlighted text would lie within this article. So, if I highlight the text "everyone!", I could obtain that text using the getSelection()
function:
var selection = window.getSelection();
What I'm unsure about is how I can then find the start and end indices of the text I highlighted within the larger article text. What function can I use to find the start and end indices of the text everyone!
within the article text Hi there, everyone!
? Thanks.