可用String.replace()配合动态正则替换敏感词:先转义元字符,再拼接去重词表构造/gi正则,最后按需脱敏。

可以用 String.replace() 配合动态构建的正则表达式,把敏感词列表转成带全局(g)和忽略大小写(i)标志的正则对象,再统一替换。关键在于正确转义敏感词中的正则特殊字符,避免语法错误。
1. 敏感词需转义正则元字符
直接把含 .、*、?、+、(、) 等的词塞进正则会出错。必须先对每个词做转义处理:
- 用
RegExp.escape(ES2024+ 原生支持)或手动实现转义函数 - 常见手动转义写法:
word.replace(/[.*+?^${}()|[]\]/g, '\$&') - 例如
"user.name"→"user.name",才能安全参与正则构造
2. 构造动态正则表达式
把转义后的敏感词用 | 拼接,再包裹进 new RegExp(..., 'gi'):
- 拼接前确保数组去重、过滤空字符串:
[...new Set(words.filter(w => w.trim()))] - 拼接后加括号可提升匹配稳定性:
new RegExp(`(${escapedWords.join('|')})`, 'gi') - 注意:若敏感词含中文、emoji,无需额外编码,UTF-8 字符 JS 正则原生支持
3. 替换时保留原始格式或脱敏处理
replace() 第二个参数可用字符串或函数,灵活控制脱敏效果:
- 全替换成星号:
text.replace(regex, '*' .repeat(match.length)) - 首尾保留、中间掩码:
text.replace(regex, match => match[0] + '*'.repeat(match.length - 2) + match[match.length - 1]) - 统一替换成指定占位符(如
[已屏蔽]),适合日志或审核场景
4. 完整示例代码
(兼容旧环境,不依赖 RegExp.escape)
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[]\]/g, '\$&');
}
<p>function cleanSensitive(text, sensitiveWords) {
if (!Array.isArray(sensitiveWords) || sensitiveWords.length === 0) return text;</p><p>const escaped = sensitiveWords
.filter(word => typeof word === 'string' && word.trim())
.map(word => escapeRegExp(word.trim()));</p><p>if (escaped.length === 0) return text;</p><p>const pattern = new RegExp(<code>(${escaped.join('|')})</code>, 'gi');
return text.replace(pattern, (match) => '*'.repeat(match.length));
}</p><p>// 使用
const content = "他的邮箱是 user.name@example.com,电话 138<strong><strong>1234";
const words = ["user.name", "138", "example.com"];
console.log(cleanSensitive(content, words));
// → "他的邮箱是 <strong><strong>**</strong></strong></strong></strong>,电话 ****1234"

















