使用正则表达式过滤用户生成的内容

创建一个包含敏感词汇的数组sensitiveWords 

_sendCommentHandle函数中,使用filterSensitiveWords函数过滤content(需要过滤的内容)

在你的项目中,创建一个名为filter.js的文件,并在其中添加以下代码:

//敏感词库:
const sensitiveWords = ['badword1', 'badword2', 'badword3'];
//创建过滤函数:
function filterSensitiveWords(text, sensitiveWords) {
  const regexStr = sensitiveWords.map(word => `\\b${word}(s|es)?`).join("|");
  const regex = new RegExp(regexStr, "gi");
  return text.replace(regex, (match, p1) => {
    return p1 ? "***" + p1 : "***";
  });
}

export default {
  sensitiveWords,
  filterSensitiveWords,
};

导入:

import filter from '@/filter';

开始过滤:

content:需要过滤的内容,

filteredContent:过滤之后的内容

const filteredContent = filter.filterSensitiveWords(content, filter.sensitiveWords);

有需求判断有没有违禁词的可以使用 includes() 函数检查 filteredContent 是否包含 "***"(表示敏感词)继续加以下代码:

const hasSensitiveWord = this.filteredContent.includes("***");

判断 hasSensitiveWord 就可以了 

猜你喜欢

转载自blog.csdn.net/weixin_44523517/article/details/130026091