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
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)
working demo
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);
You could use:
"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");
Which will return:
"Foo bar <em>cat</em>"
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.
You can do straight-up replace by using a replace function:
str.replace(/cat/ig, function replace(match) {
return '<em>' + match + '</em>';
});