Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap words in tags, keep markup

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

like image 538
spacevillain Avatar asked Nov 04 '22 22:11

spacevillain


1 Answers

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);
like image 173
Sepehr Avatar answered Nov 11 '22 05:11

Sepehr