You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript检测字符串是否包含数组中的单词并将其替换

问题排查
  • 作用域错误:Array.some() 回调的string参数仅在回调函数内部有效,你在if代码块中直接调用会抛出string is not defined的运行错误
  • 逻辑不全:现有写法只能判断是否存在敏感词,无法处理单条消息包含多个不同敏感词、同一个敏感词多次出现的场景
修复后代码
// 敏感词数组
const blocked = [
  "inappropriate word one",
  "inappropriate word two",
];

let message = "the message has an inappropriate word one";

// 遍历所有敏感词逐一全局替换
blocked.forEach(blockedWord => {
  // 构造全局正则匹配所有对应敏感词的出现位置
  const matchReg = new RegExp(blockedWord, 'g');
  message = message.replace(matchReg, "blocked");
})

console.log(message); // 输出:the message has an blocked
可选优化项

如果需要避免误伤包含敏感词的正常组合词(例如敏感词为cat时,不替换category中的匹配内容),可以给正则增加单词边界标识:

const matchReg = new RegExp(`\\b${blockedWord}\\b`, 'g');

内容的提问来源于stack exchange,提问作者wneyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:54:07