1

Hi i am not able to replace the highlighted text..here is the code of my sample which just does highlighting:

CSS:

.highlight
{
background-color:yellow;
}

JS:

function highlight(text)
{
   var inputText = document.getElementById("inputText");
    var innerHTML1 = inputText.innerHTML;
    var index = innerHTML1.indexOf(text);
    if ( index >= 0 )
    { 
        innerHTML1 = innerHTML1.substring(0,index) + "<span class='highlight'>" + innerHTML1.substring(index,index+text.length) + "</span>" + innerHTML1.substring(index + text.length);
        inputText.innerHTML = innerHTML1; 

    }

}

HTML:

<button onclick="highlight('fox')">Highlight</button>


<div id="inputText">
The fox went over the fence
</div>

Let me know the code for replacing the highlighted text..

While googling, i have got one link..but it is creating a new node..here is the link http://stackoverflow.com/questions/3997659/replace-selected-text-in-contenteditable-div?rq=1

Unsigned
  • 9,640
  • 4
  • 43
  • 72
sree
  • 535
  • 4
  • 12
  • 26
  • 2
    Seems to be working fine for me: http://jsfiddle.net/sN9sA/ What would you like to replace the highlighted text with? Here's one that replaces the selected text with the second parameter: http://jsfiddle.net/sN9sA/1/ – Mark Jan 20 '14 at 09:54

1 Answers1

1

If you want to highlight and replace, you only have to update a single line.

The second line of this snippet (line breaks for convenience) is the highlighted text. In your original snippet you use the the same part of the text your search matched. Replace it with something else and voilà:

innerHTML1 = innerHTML1.substring(0, index)
             + "<span class='highlight'>" + "Fynn the fox" + "</span>" 
             + innerHTML1.substring(index + text.length);

And the matching fiddle.

Or, a combination, which could look like this:

innerHTML1 = innerHTML1.substring(0, index)
             + "<span class='highlight'> [Match: " + innerHTML1.substring(index, index + text.length)
             + "]</span>" + innerHTML1.substring(index + text.length);
MildlySerious
  • 8,750
  • 3
  • 28
  • 30