Link to home
Start Free TrialLog in
Avatar of Lmillard
Lmillard

asked on

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
Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

Can you try this

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

Let me know if this helps
ASKER CERTIFIED SOLUTION
Avatar of kadaba
kadaba
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Lmillard
Lmillard

ASKER

Hi, sorry this didn't work, it still messes with text between the <> chars.
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