将单词包装在标签中,保留标记

Wrap words in tags, keep markup

本文关键字:保留 标签 单词 包装      更新时间:2023-09-26

例如,我有一个带有标记的字符串(来自html节点):

hello, this i sdog

"h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og"
在其中

找到一些单词(让我们说"hello"和"dog"),将它们包装在一个跨度中(突出显示)并保存所有标记的最正确方法是什么?

所需的输出是这样的(注意正确关闭的标签)

<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>

看起来和它应该的一样:

hellothis i sdog

来了:

//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);