node.js - 正则表达式替换文本数组中的主题标签
问题描述
我尝试通过主题标签用关键字替换文本并从数组中删除使用的单词。
我的数组:
['Test', 'NodeJS', 'regex']
在这里,使用 NodeJS 进行测试以尝试正则表达式!
变得:
在这里,#Test with #NodeJS 尝试 #Regex !
你能指导我如何使用 NodeJS 和正则表达式来做到这一点吗?
解决方案
您可以使用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);
如果您的数组包含带有需要转义的特殊字符的字符串,则首先按照此 Q&A中的说明进行转换。
如果您只想替换特定标记的第一次出现,则删除“g”修饰符。
推荐阅读
- batch-file - 如何仅将 cmd 中的特定文件移动到另一个文件夹?
- java - 为什么 Full GC 不能释放一些内存,但 JVMTI 触发的 ForceGarbageCollection 可以
- python - 类对象的Python内置函数?
- regex - 需要使用带有脚本标签的正则表达式检测 googletagmanager 文本
- aws-lambda - AWS Lambda 的:SAM 部署 ...识别和删除旧的 S3 包版本?
- javascript - 任务:app:transformClassesAndResourcesWithR8ForRelease FAILED React Native
- hadoop - 用于从 Sftp 服务器读取数据的 CDAP Source 插件
- android-studio - 如何解决这个 Gradle Build 我的问题?
- optimization - 如何在没有目标值的情况下通过深度学习优化模拟指标?
- kibana - 显示缺失字段的计数