For example I have a string with markup (from html node):
hello, this is dog
"h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og"
What is the most correct way to find some words in it (let's say "hello" and "dog"), wrap them in a span (make a highlight) and save all the markup?
Desired output is something like this (notice properly closed tags)
<span class="highlight">h<em>e<strong>llo</strong></em></span><strong>,</strong> <em><strong>thi</strong>s<em> i</em><strong>s <span class="highlight"><strong>d</strong>og</span>
Looks the same as it should:
hello, this is dog
Here you go:
//Actual string
var string = "h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og";
//RegExp to cleanup html markup
var tags_regexp = /<\/?[^>]+>/gi;
//Cleaned string from markup
var pure_string = string.replace(tags_regexp,"");
//potential words (with original markup)
var potential_words = string.split(" ");
//potential words (withOUT original markup)
var potential_pure_words = pure_string.split(" ");
//We're goin' into loop here to wrap some tags around desired words
for (var i in potential_words) {
//Check words here
if(potential_pure_words[i] == "hello," || potential_pure_words[i] == "dog")
//Wrapping...
potential_words[i] = "<span class=\"highlight\">" + potential_words[i] + "</span>";
}
//Make it string again
var result = potential_words.join(" ");
//Happy endings :D
console.log(result);
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