1

How can I get the index of selected text in HTML using Javascript? For example, in an HTML file, there is paragraph like the following:

I am living in India. India is the very beautiful country.

Now if the user selects India in the first sentence then there should be an alert 5 and if the user selects India of second line then there is an alert 6.

How can I get the index of the word that the user selected?

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
  • 3
    Can you provide any example code that you written and doesn't work? That way we could help you more easily Also, counting the words before the one you are selecting isn't so hard to do once you get the selected content – Luke Morgan Jun 17 '12 at 19:05
  • 1
    I'm pretty sure it can't be done. well not easily that's for sure. – gdoron Jun 17 '12 at 19:08
  • It is possible! Even if this other question don't give you the hole answer, it may help: http://stackoverflow.com/questions/5176761/get-selected-text-position – danijar Jun 17 '12 at 19:10
  • @gdoron: It can be done. http://jsfiddle.net/timdown/ArMHy/ – Tim Down Jun 18 '12 at 00:00

2 Answers2

3

You could do this with the new TextRange module of my Rangy library. Rangy's Range object has moveStart() and moveEnd() methods which allow you to expand the range a word at a time in either direction.

Here's a demo: http://jsfiddle.net/timdown/ArMHy/

Code:

var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);

    // Expand the range to contain the whole word
    range.expand("word");

    // Count all the preceding words in the document
    var precedingWordCount = 0;
    while (range.moveStart("word", -1)) {
        precedingWordCount++;
    }

    // Display results
    alert("Selection starts in word number " + (precedingWordCount + 1));        
}
Guido
  • 46,642
  • 28
  • 120
  • 174
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

If you want to find a string by its index, you can use-

string.match(regularExpression)[index]

Parameter Values-

regularExpression = Required. The value to search for, as a regular expression.

index = index of the regularExpression.

Now you can consider this as an object and assign event handlers to it.

Ash
  • 3,431
  • 2
  • 15
  • 15