js实现关键字过滤
实现关键字过滤的方法
使用正则表达式进行匹配
可以通过正则表达式来检查字符串中是否包含特定的关键字。这种方法简单直接,适用于基础过滤需求。
function filterKeywords(text, keywords) {
const regex = new RegExp(keywords.join('|'), 'i');
return regex.test(text);
}
const text = "This is a sample text containing forbidden word";
const keywords = ["forbidden", "blocked", "restricted"];
console.log(filterKeywords(text, keywords)); // true
替换敏感关键字
如果需要将敏感词替换为其他字符(如星号),可以使用字符串的替换方法。

function replaceKeywords(text, keywords) {
keywords.forEach(keyword => {
const regex = new RegExp(keyword, 'gi');
text = text.replace(regex, '*'.repeat(keyword.length));
});
return text;
}
const text = "This is a sample text containing forbidden word";
const keywords = ["forbidden", "blocked", "restricted"];
console.log(replaceKeywords(text, keywords)); // "This is a sample text containing * word"
使用数组的some方法进行过滤
可以通过数组的some方法来检查文本中是否包含任意一个关键字。

function hasKeywords(text, keywords) {
return keywords.some(keyword => text.toLowerCase().includes(keyword.toLowerCase()));
}
const text = "This is a sample text containing forbidden word";
const keywords = ["forbidden", "blocked", "restricted"];
console.log(hasKeywords(text, keywords)); // true
结合DOM操作实现前端过滤
在网页中,可以通过监听输入事件来实时过滤关键字。
document.getElementById('inputField').addEventListener('input', function(e) {
const keywords = ["forbidden", "blocked", "restricted"];
const text = e.target.value;
const hasForbidden = keywords.some(keyword => text.includes(keyword));
if (hasForbidden) {
alert("Forbidden keyword detected!");
e.target.value = '';
}
});
使用第三方库
对于更复杂的需求,可以考虑使用第三方库如bad-words,它提供了更全面的过滤功能。
const Filter = require('bad-words');
const filter = new Filter();
console.log(filter.clean("This is a bad word")); // "This is a * word"






