How do I change this
var html = '<开发者_JAVA技巧div>doe, john (Likes pizza)</div>'
To this:
var result = '<div>doe, john <span class="myspan">(Likes pizza)</span></div>'
to find the parens (...)
and wrap it with a <span>
In the console of 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>"
Edit - so that it finds any text inside parens, and not just "Likes pizza".
Edit2 - as described in the comments, it can be broken, e.g. with s = "<div class="Eric (likes breaking things)"> >>doe, john ((Likes) nested regex)</div>";
This will handle your example:
"<div>doe, john (Likes pizza)</div>".replace(/(\([^)]*\))/g,
"<span class=\"myclass\">$1</span>")
It will capture anything between an open parenthesis and the next close paren, and uses a backreference to reinsert it with the <span>
around it.
精彩评论