Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex - How to wrap matches with tag?

I have a string in JavaScript in which I'd like to find all matches of a given phrase and wrap them with a tag. I haven't been able to find the right regex method here to replace a case insensitive phrase and replace it with itself with additional text around it. For example:

Input string:

"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."

Case insensitive phrase: "cat"

Output string:

"I like to play with <em>cat</em>s, as does <em>Cat</em>hy, who is a member of A<em>CAT</em>A, which is the American <em>Cat</em> And Tiger Association."

So, basically, inject <em></em> around any matches. I can't just do a straight-up replace, because I'll lose the original case in the input string.

like image 506
Hymen Collector Avatar asked Apr 13 '15 23:04

Hymen Collector


1 Answers

You could use:

"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");

Which will return:

"Foo bar <em>cat</em>"
like image 154
Josh Crozier Avatar answered Nov 15 '22 15:11

Josh Crozier