I'm looking for a way to search through HTML and surround keywords with an <em> tag. I would like to search through a list of words that show up regularly on a series of pages.
ex. : search for [foo, bar]
html before:
....
<li>Lorem ipsum dolor sit amet</li>
<li>consectetur FOO adipiscing elit</li>
<li>Ut at convallis nisl BAR</li>
....
html after:
....
<li>Lorem ipsum dolor sit amet</li>
<li>consectetur <em>FOO</em> adipiscing elit</li>
<li>Ut at convallis nisl <em>BAR</em></li>
....
The text I'm searching will be static once it has loaded, it will always be in a list tag if that helps, and the keywords can be defined within the javascript, so I don't think the answer should be too hard to find. I've found a couple similar topics in here, but nothing quite like what I'm trying for and usually too complicated to alter with my limited skills.
The goal is to have the script added to a series of pages to avoid hand coding all of the emphasis tags, and then styling the tags with CSS.
Any help or links to similar queries would be appreciated!
See below for an implementation of the request:
// Keys
var keys = ["foo", "bar"];
// Create regular expression for a global and dynamic search and replace
var pattern = [];
for (var i=0; i<keys.length; i++) {
// Create RegExp. This section is needed to deal with special chars
pattern.push(keys[i].replace(/([[^$.|?*+(){}])/g, "\\$1"));
}
pattern = "\\b(" + pattern.join("|") + ")\\b";
pattern = new RegExp(pattern, "g"); //Replace g by gi for case-insensitivity
var li = document.getElementsByTagName("li");
for (var i=0, l=li.length; i<l; i++) {
li[i].innerHTML = li[i].innerHTML.replace(pattern, "<em>$1</em>");
}
A regular expression is used, so that the keys don't interfere with each other. If a normal search and replace, without a RegExp, is used, the following keys will interfere with each other: "cowsayMoo" "cowsay". Without a RegExp, the result will be: <em><em>cowsay</em>Moo</em>. However, since weŕe using a RegExp, this problem is solved.
Link:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With