如何解决将双括号内的子字符串替换为javascript中的其他字符串
尝试将双括号内的子字符串替换为其他字符串。 例如,假设字符串
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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。