【发布时间】:2021-06-01 17:00:48
【问题描述】:
我有一个带有单词的字符串,后跟一个冒号。我需要用对象中的值替换该字符串中的冒号。我能够提取出冒号词,但不确定在字符串中替换它的最佳方式。
这就是我所拥有的:
const string = 'This is :state :buttonName by :name';
const buttonName = 'button link';
const data = {
state: 'Alabama',
name: 'Arun'
}
const res = string.match(/:[a-zA-Z]+/g).map(i => i.replace(':', ''))
console.log(res)
// This is Alabama button link by Arun
最终结果应该是
This is Alabama button link by Arun
请指教。
【问题讨论】:
-
我们正则表达式全局标志
replace(/:/g, '') -
当然它不是
Can ES6 template literals be substituted at runtime (or reused)?的重复,因为这里的问题在于匹配特定格式的标签(以:开头,然后只包含字母 - 不是该线程中的情况)和用“字典”中的项目替换它们。 How to replace all occurrences of a string in JavaScript 根本不相关。
标签: javascript regex string