在两个字符之间替换多个字符串

时间:2019-03-19 22:02:46

标签: javascript regex replace

str = “Here are \*\*text1\*\* and \*\*text2\*\* replace those **texts.”

console.log(str.replace(/\*\*.*\*\*/, ‘replaced’)); // Here are replaced texts.

它应该显示“Here are replaced and replaced replace those **texts.”

注意-它应该处理**之间的动态字符串,而不仅仅是text1和text2

1 个答案:

答案 0 :(得分:0)

*之后,您必须转义?并使用.*进行非贪婪匹配:

const func = str => str.replace(/\*\*.*?\*\*/g, 'replaced');

console.log(func('Here are **text1** and **text2** replace those **texts.'));
console.log(func('Here is **some longer text** **'));