How to wrap an HTML tag around specific text

How do i change this

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

For this:

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

to find parens (...)and wrap it with<span>

+3
source share
2 answers

In the Chromium console:

>> 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 he finds any text inside parens, and not just "Loves pizza."

Edit2 - as described in the comments, it can be broken, for example. withs = "<div class="Eric (likes breaking things)"> >>doe, john ((Likes) nested regex)</div>";

+3
source

This will handle your example:

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

It will capture anything you want, between the open bracket and the closest one next to it, and use the backlink to re-enter it using <span>around it.

+1
source

All Articles