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

llo,th s i s og

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

看起来应该一样:

llo

最佳答案

干得好:

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

关于javascript - 将标签中的文字换行,保留标记,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10872014/

10-14 14:51
查看更多