ello, thi<...">

Wrap words in tags, keep marking up

For example, I have a line with markup (from html node):

he llo, thi s i sd og

"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 (say, “hello” and “dog”), wrap them in the gap (make a selection) and save all the markup?

The desired output is something like this (note the 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>

It looks the same as it should:

He llo , thi s i sd og

+5
source share
1 answer

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);
+2
source

All Articles