I am a iPhone app developer.I am changing the color of selected text. This is working fine for me. But when there are few repeated words for example 

> 
> Hi All.Hello world.I am iPhone app developer.Hello world.Stack overflow.Hello world.
> 
> 
> 

Here 'Hello' text is repeating. When i am selecting last 'Hello' text it is giving me first 'Hello' text index. I tried `indexOf(),search()` and `anchorOffset()` but this is not working.

Following is my code.

```
function heighlightText(data) {
    var selectedText = window.getSelection();

    var textd=$("#data").html(); // this will give me whole text.

    var normalText = $("#data").text();
    var startPosition = normalText.search(selectedText);                        // this will give selected text start position.
    var getPosition = selectedText.toString();
    var endPosition = parseInt(getPosition.length) + parseInt(startPosition);   // this will give selected text end position.

    var textToReplace = "<span id='" + startPosition + "' class='highlightedText' onclick=\"myOnclikFunction('"+selectedText+"')\"> "+selectedText+"</span>";

    var startPart = textd.substr(0,startPosition);
    var lastPart = textd.substr(endPosition,textd.length);
    var reT = startPart + textToReplace + lastPart;

    $("#data").html(reT);
}

```

Hy HTML:

```
<style type = "text/css">
    #data {
        font-size : 20px;
        color : black;
    }

    .highlightedText {
        background-color : red;
    }
</style>

<body>
    <div id = "data" >Lots of text here...
    <div/>
</body>

```

Can any one suggest solution for this.
Thanks in advance.