Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript中具有多个匹配项的正则表达式替换_Javascript_Regex - Fatal编程技术网

Javascript中具有多个匹配项的正则表达式替换

Javascript中具有多个匹配项的正则表达式替换,javascript,regex,Javascript,Regex,给定以下字符串: var text = 'foo bar foo bar hello world'; 我尝试输出字符串: <mark>foo</mark> <mark>bar</mark> <mark>foo</mark> <mark>bar</mark> hello world foobar foobar你好世界 通过使用正则表达式: var pattern = /(foo)|(bar)/g;

给定以下字符串:

var text = 'foo bar foo bar hello world';
我尝试输出字符串:

<mark>foo</mark> <mark>bar</mark> <mark>foo</mark> <mark>bar</mark> hello world
foobar foobar你好世界
通过使用正则表达式:

var pattern = /(foo)|(bar)/g;
text.replace(pattern, '<mark>$1</mark>');
var模式=/(foo)|(bar)/g;
文本。替换(模式“$1”);
但结果是:

<mark>foo</mark> <mark>foo</mark> hello world
foo foo hello world


如何在替换参数中指定所有匹配项?如果我提供多个(例如100个)匹配,会怎么样?我是否必须在替换中指定所有匹配项(
$1
$100
)?

问题在于
/(foo)|(bar)/g
位于第二个捕获组中。作为替代,只使用第一个捕获的组

您可以使用一个捕获的组,该组将同时具有
foo
bar
。我还建议使用
\b
单词边界来匹配
foo
bar
作为完整单词,而不是另一个单词的一部分,如
foobar

text.replace(/\b(foo|bar)\b/g, '<mark>$1</mark>');
text.replace(/\b(foo | bar)\b/g,$1');
var text='foo bar foo bar hello world';

document.body.innerHTML=text.replace(/\b(foo | bar)\b/g,$1')问题出在
/(foo)|(bar)/g
位于第二个捕获组中。作为替代,只使用第一个捕获的组

您可以使用一个捕获的组,该组将同时具有
foo
bar
。我还建议使用
\b
单词边界来匹配
foo
bar
作为完整单词,而不是另一个单词的一部分,如
foobar

text.replace(/\b(foo|bar)\b/g, '<mark>$1</mark>');
text.replace(/\b(foo | bar)\b/g,$1');
var text='foo bar foo bar hello world';

document.body.innerHTML=text.replace(/\b(foo | bar)\b/g,$1')您可以改进正则表达式以扩展捕获组:

/(foo)|(bar)/g
进入:

/(foo | bar)/g
其结果是:

“foo bar foo bar hello world”
这是通过使
$1
同时捕获
foo
bar
而不是只捕获
foo
来实现的


但是,如果您不能做到这一点,您确实必须手动指定所有捕获组

您可以改进您的正则表达式以扩展捕获组:

/(foo)|(bar)/g
进入:

/(foo | bar)/g
其结果是:

“foo bar foo bar hello world”
这是通过使
$1
同时捕获
foo
bar
而不是只捕获
foo
来实现的

但是,如果您不能做到这一点,那么实际上必须手动指定所有捕获组