Reputation: 151
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.
Upvotes: 15
Views: 10638
Reputation: 626758
One needs no capturing group around the whole regex because there is a $&
placeholder that refers to the whole match from the string replacement pattern:
"Foo bar cat".replace(/cat/ig, "<em>$&</em>");
^^
See the Specifying a string as a parameter section:
$&
Inserts the matched substring.
Thus, no need of any callback methods or redundant regex constructs.
Upvotes: 5
Reputation: 30995
You can solve it very simple, just use a capturing group
with the word
you want, and then use the replacement string <em>$1</em>
. You can use a regex like this:
(cat)
Below, you can see in green the matches (capturing the word cat
insensitively) and in the substitution section
you can see the replacements.
You can use this code:
var re = /(cat)/ig;
var str = '"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."\n';
var subst = '<em>$1</em>';
var result = str.replace(re, subst);
Upvotes: 2
Reputation: 240908
You could use:
"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");
Which will return:
"Foo bar <em>cat</em>"
Upvotes: 18
Reputation: 7599
You can do straight-up replace by using a replace function:
str.replace(/cat/ig, function replace(match) {
return '<em>' + match + '</em>';
});
Upvotes: 5