gpt4 book ai didi

javascript - 将单词包裹在标签中,保留标记

转载 作者:太空狗 更新时间:2023-10-29 16:37:24 32 4
gpt4 key购买 nike

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

hello, thiss is dog

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

看起来和它应该的一样:

hello,s dog

最佳答案

给你:

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

32 4 0