我尝试用标签替换文本,并从数组中删除使用的单词。
我的阵列:
['Test', 'NodeJS', 'regex']
这里,用NodeJS测试regex!
变成:
在这里,用NodeJS测试Regex!
你能指导我如何使用NodeJS和regex吗?
你可以用它 reduce , new RegExp 和 replace 使用回调函数(用于将单词标记为已用):
reduce
new RegExp
replace
var tags = ['Test', 'NodeJS', 'notfound', 'regex'] var s = "Here, test with NodeJS to try regex !"; s = tags.reduce((acc, tag, i) => acc.replace(new RegExp("\\b" + tag + "\\b", "gi"), () => { tags[i] = null; return "#" + tag; }), s); tags = tags.filter(Boolean); console.log(s); console.log(tags);
如果数组包含需要转义的具有特殊字符的字符串,请首先对其进行转换,如中所述 this Q&A .
如果您只想替换 第一 出现特定标记,然后删除“g”修饰符。