sharataka
sharataka

Reputation: 5132

How to return position of string in javascript?

I am trying to include functionality that will enable a user to highlight text and have that text returned. I would also like to return the location of that text within #textcontainer div.

My issue: if the user highlights the second 'and' in the text below, position will equal the indexOf the first 'and' in the div instead of the second. How do I change this to have position return the position of the second 'and' (the one that is highlighted)?

    <div id = 'textcontainer'>
        and second third and
    </div>


     // beginning of highlight js
    $('#highlight').click(function (e) {
        e.preventDefault();

        // get highlighted text
        var selection = window.getSelection();
        var txt = selection.toString();
        console.log(txt);

        fulltext = $("#textcontainer").text();
        console.log(fulltext);

        position = fulltext.indexOf(txt);
        console.log(position);

    })
  // end of highlight js

Upvotes: 1

Views: 214

Answers (1)

Linus Thiel
Linus Thiel

Reputation: 39223

You're in luck, since window.getSelection() returns a Selection object, which in turn has a getRangeAt method, which you can use like so:

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

var start = range.startOffset, end = range.endOffset;

Edit: Note that IE has a completely different selection API. For cross-browser compatibility, you may want to take a look at Rangy (note: I don't have any experience with the library).

Edit 2: See this answer for some jQuery plugins.

Upvotes: 2

Related Questions