Using Javascript RegExp to highlight a search term in innerHTML


I have a search results page where I would like to highlight the search term where it appears within the page.

I have placed the search results within a div tag with id so can reference this, do a regexp and it works fine but I need to exclude all html/xml tags from the function. Can anyone help with this.

So far I have the following which works but if the search term was 'able' this would trash all table tags!

Note: The search term is being generated dynamically so I have entered the static string of Able as a demonstration.

var str = document.getElementById('srchresult').innerHTML;
document.getElementById('srchresult').innerHTML = str.replace(/Able/gi, "<strong style='color:#CC0000'>Able</strong>");

Who is Participating?
Gurvinder Pal SinghCommented:
Can you try this

var myArray = str.replace(/[^a-z]*(able)/m,"<Str>able</Str>")

Let me know if this helps
LmillardAuthor Commented:
Hi, sorry this didn't work, it still messes with text between the <> chars.
Gurvinder Pal SinghCommented:
Given that
var str = document.getElementById('srchresult').innerHTML;
Why dont you take str as a xml and parse it using XML DOM, and then only take values from it and make it <strong>?

You can use the following link for reference
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.