简体   繁体   中英

Regex replacement in Javascript with multiple matches

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 (eg 100) matches? Do I have to specify all matches ( $1 to $100 ) in the replacement?

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>'); 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM