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.
You could use:
"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");
Which will return:
"Foo bar <em>cat</em>"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With