如何批量匹配数组内关键词并替换字符串中的对应内容
实现方案
方案1:遍历词汇数组逐次替换
适合词汇量不大的场景,逻辑简单易维护:
let words: string[] = ['cat','rat','bat']; let text: string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." let newText = text; words.forEach(word => { // 正则加g标志实现全局替换,不加的话只会替换每个词汇的第一个匹配项 const matchReg = new RegExp(word, 'g'); newText = newText.replace(matchReg, 'TEST'); })
如果不需要区分大小写匹配,可以把正则标志改为gi。
方案2:合并为单个正则一次性替换
词汇量较大时效率更高,仅需要扫描一次文本即可完成所有替换:
let words: string[] = ['cat','rat','bat']; let text: string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." // 把所有词汇用|拼接成正则匹配规则 const matchReg = new RegExp(words.join('|'), 'g'); const newText = text.replace(matchReg, 'TEST');
如果你的词汇列表里包含+、*、?这类正则特殊字符,需要先对词汇做转义处理避免匹配异常:
// 正则特殊字符转义工具函数 const escapeRegExp = (str: string) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const matchReg = new RegExp(words.map(escapeRegExp).join('|'), 'g');
后续高亮改造提示
后续要实现高亮功能时,直接把替换的占位文本换成带样式的标签即可,比如前端场景可以这么写:
// $&代表匹配到的原词汇,会保留原词内容同时包裹高亮标签 const newText = text.replace(matchReg, '<span class="highlight">$&</span>');
给.highlight类设置对应的高亮样式就能实现需求。
内容的提问来源于stack exchange,提问作者Pegasus008
相关产品推荐
相关产品推荐

