替换两个其他字符之间的多个相同字符的出现

时间:2017-06-24 09:34:05

标签: javascript regex

如果角色出现在两个特定的角色之间,我该如何替换?即使之前和之后都有文字吗?

例如,如果我有这样的字符串:

var text = "For text `in between two backticks, replace all #es with *s`. It should `find all such possible matches for #, including multiple ### together`, but shouldn't affect ### outside backticks."

我想要的输出是:

"For text `in between two backticks, replace all *es with *s`. It should `find all such possible matches for *, including multiple *** together`, but shouldn't affect ### outside backticks."

我已获得以下代码:

text = text.replace(/`(.*?)#(.*?)`/gm, "`$1*$2`");

1 个答案:

答案 0 :(得分:3)

使用一个匹配反引号的简单/`[^`]+`/g正则表达式,然后使用除反引号之外的1个字符,然后再使用反引号,并替换回调中的#



var text = "For text `in between two backticks, replace all #es with *s`. It should `find all such possible matches for #, including multiple ### together`, but shouldn't affect ### outside backticks.";
var res = text.replace(/`[^`]+`/g, function(m) {
  return m.replace(/#/g, '*');
});
console.log(res);