Reputation: 2556
Given the following string:
var text = 'foo bar foo bar hello world';
I tried outputting the string:
<mark>foo</mark> <mark>bar</mark> <mark>foo</mark> <mark>bar</mark> hello world
by using regex:
var pattern = /(foo)|(bar)/g;
text.replace(pattern, '<mark>$1</mark>');
But the output became:
<mark>foo</mark> <mark>foo</mark> hello world
How could I specify all matches in the replacement parameter? What if I give multiple (e.g. 100) matches? Do I have to specify all matches ($1
to $100
) in the replacement?
Upvotes: 0
Views: 68
Reputation: 2779
You can improve your RegEx to extend the capture groups instead:
/(foo)|(bar)/g
Into:
/(foo|bar)/g
Which results in:
"<mark>foo</mark> <mark>bar</mark> <mark>foo</mark> <mark>bar</mark> hello world"
This works by making the $1
capture both foo
and bar
instead of just foo
.
However, if you couldn't do this, you would indeed have to specify all the capture groups manually
Upvotes: 1
Reputation: 87203
The problem is in the /(foo)|(bar)/g;
, bar
is in second captured group. And in replacement, only first captured group is used.
You can use a single captured group which will have both foo
and bar
in alteration. I'll also suggest to use \b
word boundary to match foo
and bar
as complete words and not part of another word like foobar
.
text.replace(/\b(foo|bar)\b/g, '<mark>$1</mark>');
var text = 'foo bar foo bar hello world';
document.body.innerHTML = text.replace(/\b(foo|bar)\b/g, '<mark>$1</mark>');
Upvotes: 4