使用简单的 angular 过滤器替换输入字符串中所有出现的特定字符串,而不考虑大小写和空格

Using simple angular filter to replace all occurences of certain strings in input string regardless of case and whitespaces

在我的网站上,我有一个评论区,人们可以在这里写任何他们想写的东西。为了防止垃圾邮件和不认真的评论,我以这种方式使用 angular 过滤器:

<span>{{comment | mouthWash}}</span>

angular 过滤器获取包含禁用词的数组并扫描输入字符串并替换所有出现的获取词。过滤器的代码如下:

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>

这工作得很好,只是我想让它忽略空格,以使其更加防弹。我对正则表达式没有太多经验,所以如果有人对此有简单的解决方案,我将不胜感激。

只需将 new RegExp(word, "ig"); 更改为 new RegExp("ig");

工作示例:

var words = ['pig', 'dog', '', ' ', 'cow'];

words.forEach(function(word) {
     var regEx = new RegExp("ig");
     word = word.replace(regEx, "mooh");
    console.log(word);
});

输出:

    "pmooh"
    "dog"
    ""
    " "
    "cow"

这是我最终得到的代码:

    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 str = word.substring(0,1)+"\s*";
          for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\s*";
          str = str + word.substring(word.length - 1,word.length);
          var regEx = new RegExp(str, "gi");
          input = input.replace(regEx, "mooh");
        });

        return input;
      };

    });

我创建了一个 for 循环,它会遍历禁用词的每个字符,将字符与 \s*(以便忽略空格)一起添加到字符串中。

for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\s*";

然后从字符串创建一个 regExp,通过使用 regExp 构造函数将字符串作为第一个参数,"gi" 作为第二个参数,使 regExp 成为全局的并且不区分大小写。

var regEx = new RegExp(str, "gi");

然后使用该正则表达式搜索输入字符串并将所有匹配项替换为 "mooh"。