问题描述
尝试将双括号内的子字符串替换为其他字符串。 例如,假设字符串
a = "In order to unlock this attempt,you must contact your {{teacher}}. When the attempt is unlocked by your {{teacher}},we will notify you!"
我想将a
转换为
"In order to unlock this attempt,you must contact your *coach*. When the attempt is unlocked by your *coach*,we will notify you!"
基本上,在JavaScript中将“ {{teach}}”替换为“教练”。有两个或多个要替换它。 (问题)
请在JavaScript中使用正则表达式(RegExp)进行替换。
谢谢
解决方法
对正则表达式使用String.prototype.replace()
方法。 replace方法在字符串中搜索指定的值或正则表达式,然后返回替换了指定值的新字符串。使用g
修饰符替换所有出现的指定值。替换方法string.replace(searchValue,newValue)
const a = `In order to unlock this attempt,you must contact your {{teacher}}. When the attempt is unlocked by your {{teacher}},we will notify you!`;
const ret = a.replace(/{{.*?}}/g,'*coach*');
console.log(ret);