Tom Foster
Tom Foster

Reputation: 462

Replace regex string with the same content, and a span tag around it

I'm trying to place a span around every word inside of quotes, kind of like:

$('code').html($('code').html().replace(/"(.*?)"/g, '<span>/"(.*)?"/g</span>')

I can get it to replace all quoted words with a simple string but not with the original content with a span around it. Any ideas on how this could be done? Thanks!

Upvotes: 1

Views: 1600

Answers (2)

godswearhats
godswearhats

Reputation: 2255

Try this:

str.replace(/"(\w+)"/g, '<span>$1</span>')

You use special variables ($1, $2, etc.) to refer to the first (and second, etc.) matched item in parentheses.

Upvotes: 1

Barmar
Barmar

Reputation: 781058

In the replacement string $& will get what the regexp matched, $1 will get the first capture group, $2 gets the second capture group, and so on. So:

$('code').html($('code').html().replace(/".*?"/g, '<span>$&</span>'));

Upvotes: 6

Related Questions