ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

定制你的过滤规则:bad-words添加/移除敏感词的3种实用技巧

2026/8/5 14:15:52 拓冰建站 浏览量
定制你的过滤规则:bad-words添加/移除敏感词的3种实用技巧

定制你的过滤规则:bad-words添加/移除敏感词的3种实用技巧

【免费下载链接】badwordsA javascript filter for badwords项目地址: https://gitcode.com/gh_mirrors/ba/badwords

bad-words 是一款轻量级的 JavaScript 敏感词过滤工具,能够帮助开发者轻松实现文本内容的净化处理。本文将介绍三种实用技巧,教你如何灵活添加或移除敏感词,打造符合自身需求的过滤规则。

技巧一:使用 addWords 方法动态添加敏感词

当系统默认的敏感词库无法满足需求时,addWords方法允许你随时扩充过滤列表。这个方法支持单次添加单个或多个敏感词,甚至可以通过数组批量导入。

在 lib/badwords.js 中可以看到该方法的实现:

addWords() { let words = Array.from(arguments); this.list.push(...words); // 从白名单中移除可能存在的相同词汇 words.map(word => word.toLowerCase()) .forEach((word) => { if (this.exclude.includes(word)) { this.exclude.splice(this.exclude.indexOf(word), 1); } }); }

使用示例

const Filter = require('./lib/badwords'); const filter = new Filter(); // 添加单个敏感词 filter.addWords('badword'); // 添加多个敏感词 filter.addWords('word1', 'word2', 'word3'); // 批量添加敏感词数组 const newWords = ['word4', 'word5']; filter.addWords(...newWords);

技巧二:通过 removeWords 方法将词汇加入白名单

某些场景下,你可能需要将特定词汇从过滤列表中排除,这时可以使用removeWords方法将它们加入白名单。被加入白名单的词汇会被过滤系统忽略,即使它们存在于敏感词库中。

test/removeWords.js 中的测试用例展示了具体用法:

it('Should allow you to remove words from the filter blacklist and no longer filter them', () => { filter.removeWords('Hells'); assert(filter.clean('This is a hells good test') === 'This is a hells good test'); });

使用示例

// 将"example"加入白名单 filter.removeWords('example'); // 批量添加多个白名单词汇 filter.removeWords('word1', 'word2', 'word3');

技巧三:初始化时自定义完整过滤规则

如果需要完全自定义过滤规则,可以在创建 Filter 实例时通过 options 参数进行配置。这种方式适合需要完全控制敏感词列表的场景。

lib/badwords.js 的构造函数支持多种配置选项:

constructor(options = {}) { Object.assign(this, { list: options.emptyList && [] || Array.prototype.concat.apply(localList, [baseList, options.list || []]), exclude: options.exclude || [], // 其他配置项... }) }

使用示例

// 创建一个包含自定义敏感词列表的过滤器 const customFilter = new Filter({ list: ['custom1', 'custom2', 'custom3'], // 自定义敏感词列表 emptyList: true, // 不使用默认敏感词库 exclude: ['allow1', 'allow2'] // 白名单词汇 });

总结

掌握这三种技巧,你可以轻松定制符合自身需求的敏感词过滤规则:

  • 使用addWords动态扩展敏感词库
  • 通过removeWords创建词汇白名单
  • 初始化时配置完整的自定义规则

这些方法都可以在 lib/badwords.js 中找到实现细节,同时 test/ 目录下的测试文件提供了更多使用示例。根据实际需求灵活组合这些技巧,能让 bad-words 工具发挥最大效用。

开始使用 bad-words 打造更安全的文本内容过滤系统吧!你可以通过以下命令获取项目代码:

git clone https://gitcode.com/gh_mirrors/ba/badwords

【免费下载链接】badwordsA javascript filter for badwords项目地址: https://gitcode.com/gh_mirrors/ba/badwords

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考