badwords
为例)在用户输入场景(如评论、表单、聊天)中,敏感词过滤是合规性和用户体验的关键。它能:
// 敏感词列表(可根据需求扩展)
const sensitiveWords = ["暴力", "色情", "违禁品", "脏话"];
function filterText(inputText) {
let filteredText = inputText;
sensitiveWords.forEach(word => {
// 使用正则替换为*
const regex = new RegExp(word, 'g');
filteredText = filteredText.replace(regex, '***');
});
return filteredText;
}
<input type="text" id="userInput" placeholder="请输入内容">
<button onclick="checkContent()">提交button>
<script>
function checkContent() {
const input = document.getElementById('userInput').value;
const result = filterText(input);
alert("过滤后内容:" + result);
}
script>
badwords
npm install badwords
import Filter from 'badwords';
// 创建过滤器实例
const filter = new Filter();
// 添加自定义敏感词
filter.addWords("自定义敏感词1", "自定义敏感词2");
// 过滤文本
const cleanText = filter.clean("这是一句包含脏话的文本");
console.log(cleanText); // 输出:这是一句包含****的文本
将词库存储在JSON文件中,动态加载:
// words.json
{ "sensitiveWords": ["广告", "诈骗", "政治敏感"] }
// 加载词库
fetch('words.json')
.then(response => response.json())
.then(data => sensitiveWords.push(...data.sensitiveWords));
使用Trie树算法提升匹配效率(示例代码片段):
class TrieNode {
constructor() {
this.children = {};
this.isEnd = false;
}
}
// 构建Trie树代码略(可提供GitHub源码链接)
提供可运行的HTML文件(含表单提交、过滤、高亮敏感词功能):
DOCTYPE html>
<html>
<body>
<textarea id="input" rows="4">textarea>
<button onclick="filterContent()">检测button>
<div id="result">div>
<script>
// 完整代码见:https://github.com/yourusername/sensitive-filter-demo
script>
body>
html>
问题 | 解决方法 |
---|---|
中英文混合词匹配失败 | 使用正则忽略大小写:/word/gi |
过滤速度慢 | 改用Trie树或AC自动机算法 |
误判正常词汇 | 设置白名单机制 |
需要实时更新词库 | 定期从服务器加载最新词库 |
通过本文,你已掌握两种敏感词过滤实现方案。新手建议先用badwords
库快速上手,再逐步深入优化。记得根据业务需求调整词库和匹配策略!
如有需求,直接私信留下您的联系方式。谢谢。
我的邮箱:[email protected]