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
来实现的
但是,如果您不能做到这一点,那么实际上必须手动指定所有捕获组