当前位置:首页 > JavaScript

js实现关键字过滤

2026-03-01 20:32:31JavaScript

实现关键字过滤的方法

使用正则表达式进行匹配

可以通过正则表达式来检查字符串中是否包含特定的关键字。这种方法简单直接,适用于基础过滤需求。

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

替换敏感关键字

如果需要将敏感词替换为其他字符(如星号),可以使用字符串的替换方法。

js实现关键字过滤

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方法来检查文本中是否包含任意一个关键字。

js实现关键字过滤

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"

标签: 关键字js
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue-r…

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到指…

js实现定位

js实现定位

使用Geolocation API获取当前位置 在JavaScript中,可以通过浏览器内置的Geolocation API获取用户的地理位置信息。该API需要用户授权才能访问位置数据。 if (n…