Using Javascript RegExp to highlight a search term in innerHTML

Hi,

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>");


Regards
Leigh
LmillardAsked:
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
0
 
LmillardAuthor Commented:
Hi, sorry this didn't work, it still messes with text between the <> chars.
0
 
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
http://www.w3schools.com/xml/xml_dom.asp
0
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.