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('s rchresult' ).innerHTM L;
document.getElementById('s rchresult' ).innerHTM L = str.replace(/Able/gi, "<strong style='color:#CC0000'>Able </strong>" );
Regards
Leigh
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('s
document.getElementById('s
Regards
Leigh
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi, sorry this didn't work, it still messes with text between the <> chars.
Given that
var str = document.getElementById('s rchresult' ).innerHTM L;
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
var str = document.getElementById('s
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
var myArray = str.replace(/[^a-z]*(able)
Let me know if this helps