在我的网站上,我有一个评论区,人们可以在其中写任何他们想写的东西。为了防止垃圾邮件和不严肃的评论,我以这种方式使用角度过滤器:
<span>{{comment | mouthWash}}</span>
角度过滤器获取包含禁用词的数组并扫描输入字符串并替换所有出现的获取词。过滤器的代码如下:
app.filter('mouthWash', function($http) {
var badWords;
$http.get('js/objects/bad-words.json').success(function (data) {
badWords = data;
});
return function(input) {
angular.forEach(badWords, function(word){
var regEx = new RegExp(word);
input = input.replace(regEx, "mooh");
});
return input;
};
});
bad-words.json是这样的:
["fuck", "ass", "shit", etc...]
所以作为一个例子<span>{{ "fuck this" | mouthWash}}</span>
输出为<span>mooh this</span>
这是完美的工作,除了我希望它忽略空格,使其更加防弹。我对正则表达式没有太多经验,所以如果有人对此有一个简单的解决方案,我将不胜感激。