如何围绕特定文本包装HTML标记

时间:2011-05-07 16:57:22

标签: jquery html regex

如何更改此

var html = '<div>doe, john (Likes pizza)</div>'

对此:

var result = '<div>doe, john <span class="myspan">(Likes pizza)</span></div>'

找到parens (...)并用<span>

包装

2 个答案:

答案 0 :(得分:3)

在Chromium的控制台中:

>> re = new RegExp(/\((.+)\)/);

>> s = "<div>doe, john (Likes pizza)</div>";
"<div>doe, john (Likes pizza)</div>"
>> s.replace(re, "<span class=\"myspan\">($1)</span>");
"<div>doe, john <span class="myspan">(Likes pizza)</span></div>"

>> ss2 = "<div>doe, john (Likes football)</div>";
"<div>doe, john (Likes football)</div>"
>> ss2.replace(re, "<span class=\"myspan\">($1)</span>");
"<div>doe, john <span class="myspan">(Likes football)</span></div>"

编辑 - 以便在parens中找到任何文本,而不只是“喜欢披萨”。

Edit2 - 如评论中所述,它可以被破坏,例如与s = "<div class="Eric (likes breaking things)"> >>doe, john ((Likes) nested regex)</div>";

答案 1 :(得分:1)

这将处理你的例子:

"<div>doe, john (Likes pizza)</div>".replace(/(\([^)]*\))/g,
            "<span class=\"myclass\">$1</span>")

它将捕获开括号和下一个关闭paren之间的任何内容,并使用反向引用将其重新插入其周围的<span>