Colin Ricardo
Colin Ricardo

Reputation: 17269

Select word and surrounding words with window.getSelection()

Using window.getSelection() I want to get a word selected at position n but also the words at positions n-1 and n+1.

For example:

this is a sentence

highlighted: is

word n-1: this

word n + 1: a

I understand how to do this with regex, but how can I do this kind of thing with window.getSelection()?

Upvotes: 0

Views: 607

Answers (1)

Ami Heines
Ami Heines

Reputation: 500

Do you know the structure of the HTML page? Do you control it? If not, this could be difficult.

If the selection is in one element on the page, this can be done with the help of the selected range object:

var range = window.getSelection().getRangeAt(0);

It has properties with the starting position, end position and the text of the element that the selection is in.

Then you can break the text by spaces before and after the selection position and get the word before and after the selected word.

var allWordsBefore = range.startContainer.wholeText.substr(0, range.startOffset).trim().split(' ');
var prevWord = allWordsBefore[allWordsBefore.length-1];

Similarly you can get the word after the selection.

Upvotes: 1

Related Questions