javascriptangularjsregexangularjs-filterng-filter

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


On my website I have a commentary field, where people can write whatever they want. To prevent spam and unserious comments, I'm using an angular filter in this way:

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

The angular filter fetches an array containing banned words and scans through the input string and replaces all the occurences of the fetched words. The code for the filter is as below:

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 is something like this:

["fuck", "ass", "shit", etc...]

So as an example <span>{{ "fuck this" | mouthWash}}</span> is outputted as <span>mooh this</span>

This is working perfectly, except that I want it to ignore whitespaces, to make it more bullet proof. I do not have much experience with regex, so if anyone had a simple soloution to this, I would be really grateful.


Solution

  • This is the code I ended up with:

        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;
          };
    
        });
    

    I created a for loop that would loop through every character of the banned word, adding the character together with \s* (so that spaces was ignored) to a string.

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

    Then created a regExp from the string, by using the regExp constructor with the string as first parameter and "gi" as second, to make the regExp global and case insensitive.

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

    Then that regex was used to search through input string and replace all matches with "mooh".