优化亵渎过滤器的代码

时间:2014-11-21 08:14:23

标签: javascript

我有一个聊天应用程序,我想使用亵渎过滤器。

我想出了:http://jsfiddle.net/691nruoL/4/

var chatMessage = "sex it up what the fuck tits lol fuck titsss";

// Potentially an array of hundreds of words coming from a JSON file
var badWords = ['sex', 'fUck', 'dick', 'penis', 'cum', 'tits', 'fuck'];

for (var i = 0; i < badWords.length; i++) {
    if (chatMessage.indexOf(badWords[i].toLowerCase()) !== -1) {
        chatMessage = chatMessage.replace(badWords[i].toLowerCase(), pushAsterisksForWordLength(badWords[i].length));
    }
}

function pushAsterisksForWordLength(asterisksLength) {
    var censoredWordArray = [];
    for (var i = 0; i < asterisksLength; i++) {
        censoredWordArray.push('*');
    }
    return censoredWordArray.join('');
}

console.log(chatMessage);

你会如何优化它?我觉得阵列中有很多坏词,可能会很慢。

3 个答案:

答案 0 :(得分:4)

使用regexp:

var chatMessage = "sex it up what the fuck tits lol fuck titsss";
var badWords = ['sex', 'fUck', 'dick', 'penis', 'cum', 'tits', 'fuck'];
var regExpSource = badWords.join('|');
var regExpFilter = new RegExp(regExpSource, 'ig');

console.log(regExpFilter.test(chatMessage));

并删除带星号的单词,如:

chatMessage.replace(regExpFilter, function () {
    return '****';//Don't matter what that was a word 
});

答案 1 :(得分:3)

// Prepare for search (just once)
var badWordsRE = new RegExp(badWords.join('|'), "gi");
var asterisks = "";
badWords.forEach(function(word) {
  while (word.length > asterisks.length) asterisks += "*";
});

// Search and destroy
chatMessage.replace(badWordsRE, function(word) {
  return asterisks.substring(0, word.length);
});
// => "*** it up what the **** **** lol **** ****ss"

答案 2 :(得分:0)

在&#34; bad&#34;中分配每个字母。带有星号的单词没有循环遍历单词:

chatMessage.replace(/sex|fuck|tits/gi,function( word ){
 return word.replace(/./g,'*')
});

http://jsfiddle.net/691nruoL/5/