Vue sensitive word filtering front end

Vue sensitive word filtering front end

Filtering sensitive words according to the regularity is an array of words that are more specifically stored in the js file. Vue is exported with export and then imported into the components that need to be used.

judgeBadWord(obj) {
    
    
      let word = words.words //获取敏感词的数组
      //进行遍历
      for (let i=0;i<word.length;i++) {
    
    
        /*替换全部空格*/
        // let arr = obj.replace(/\s+/g,"")
        this.contents = obj
        //gi g全局  i不分大小写
        let reg = new RegExp(word[i],"gi")
        //用indexOf 判断是否包含
        if(this.contents.indexOf(word[i]) !== -1){
    
    
          let result = this.contents.replace(reg,"***")
          this.contents = result
          return true
        }
      }
    }
    //在发送消息时进行调用就行了

At the beginning, I thought it would be fine, but when there are multiple sensitive words in the same sentence, the latter will not be filtered out and improved.

judgeBadWord(str,badWord){
    
    
		//trim() 方法不会改变原始字符串 去掉首尾空白符
          this.contents = str.trim()
          var re = ''
          //正则过滤 模版字符串 \b 是一个整单词
          for(var i=0;i<badWord.length;i++){
    
    
            if(i==forbiddenArray.length-1)
            re += `\\b${
      
      badWord[i]}\\b`
            else
            re += `\\b${
      
      badWord[i]}\\b`+"|"
          }
          var reg = new RegExp(re,"gi")
          this.contents=this.contents.replace(reg,"***")
          return this.contents
        }

At this point, I thought it was over, but there are two English words
in the sensitive word that make up hellow, which is a sensitive word, hellow word, and also a sensitive word. When inputting hellow word, helllow will become *** word won’t be able to change the string in the array by itself Adjust the position yourself and
sort the array

    //这里用map可以进行链式调用 字符串的length 从高到低排序
	let word = words.words
    this.rtn = word.map(i => ({
    
    raw: i, len: i.length}))
                .sort((p, n) => n.len - p.len)
                .map(i => i.raw)

Just record the performance aspects and optimize the shortcomings, please take care! ! ! !

Guess you like

Origin blog.csdn.net/qq_45588362/article/details/109358957