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

时间:2023-01-22 16:52:32

How do I replace a character only if it is present in between two specific others? Even if there is text before and after it?

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

For example, if I have a string like this:

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

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."

My desired output is:

我想要的输出是:

"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."

I've got the following code:

我有以下代码:

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

1 个解决方案

#1


2  

Use a simple /`[^`]+`/g regex that will match a backtick, then 1+ chars other than a backtick, and then again a backtick, and replace the # inside a callback:

使用一个简单的/`[^`] +`/ 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);

#1


2  

Use a simple /`[^`]+`/g regex that will match a backtick, then 1+ chars other than a backtick, and then again a backtick, and replace the # inside a callback:

使用一个简单的/`[^`] +`/ 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);