将双括号内的子字符串替换为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);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...