如何用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
相关产品推荐
相关产品推荐

