前言
做了个直播聊天室,但是难免有用户吞吐不干净,所以给input框增加个敏感词过滤功能,把敏感词过滤变成*号
提示:以下是本篇文章正文内容,下面案例可供参考
一、定义敏感词数据
目前没有敏感词开源的库,所以数据只能我们自己定义,比如:
const badwordsList = ["史","nmd","狗", "乱a犬"]
二、根据输入内容过滤
给input绑定input事件,可以直接获取你输入的每一个字
<el-input type="textarea" placeholder="请输入" v-model="input" @input="handleInput"></el-input>
在data里面定义好badwordsList数组
data(){
return{
badwordsList:["史","nmd","狗", "乱a犬"],
input:'',
}
}
methods里写好handleInput方法
handleInput() {
let filtered = this.input
if (this.badwordsList) {
for (const word of this.badwordsList) {
const escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const reg = new RegExp(escapedWord, "gi");
filtered = filtered.replace(reg, "*".repeat(word.length));
}
}
this.input = filtered;
},