首页 > 解决方案 > 正则表达式替换文本数组中的主题标签

问题描述

我尝试通过主题标签用关键字替换文本并从数组中删除使用的单词。

我的数组:

['Test', 'NodeJS', 'regex']

在这里,使用 NodeJS 进行测试以尝试正则表达式!

变得:

在这里,#Test with #NodeJS 尝试 #Regex !

你能指导我如何使用 NodeJS 和正则表达式来做到这一点吗?

标签: node.jsregex

解决方案


您可以使用reduce,new RegExpreplace回调函数(用于将单词标记为已使用):

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);

如果您的数组包含带有需要转义的特殊字符的字符串,则首先按照此 Q&A中的说明进行转换。

如果您只想替换特定标记的第一次出现,则删除“g”修饰符。


推荐阅读