2017-06-24 40 views
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." 

我所需的输出是:

"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`"); 
+0

所以你要替换之间的两个''的'#*'? –

+0

不,我希望它取代两个反引号(') – KarthaCoder

回答

2

使用一个简单的/`[^`]+`/g正则表达式,它将匹配一个反引号,然后1+字符而不是反引号,然后再一个backti CK,并更换#回调中:

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

相关问题