下面有一个字符串,在花括号内有一些单词,我想提取单词并将其作为数组
输入:
let string = 'Hello John \n, the time is ${time} and its ${day} of ${month} ${year}'
输出:
let keys = ["time", "day", "month", "year"]
在正则表达式中实现它的正确方法是什么。
如何用输入标签替换字符串,如下所示。
let string = 'Hello John \n, the time is <input name='time' /> and its <input name='day' /> of <input name='month' /> <input name='year' />'
答案 0 :(得分:3)
您可以捕获所有匹配的组
const string = 'Hello John \n, the time is ${time} and its ${day} of ${month} ${year}'
const regex = /\$\{(\w+)\}/g
const res = [];
let matches
while (matches = regex.exec(string)) {
res.push(matches[1]);
}
console.log(res)
关于替换,使用捕获的组(基于1的索引)的顺序,使用美元符号(.replace
)对修改后的Catupered组执行字符串$
const string = 'Hello John \n, the time is ${time} and its ${day} of ${month} ${year}'
const res = string.replace(/\$\{(\w+)\}/g, '<input name="$1"/>')
console.log(res)