Search code examples
javascriptprofanity

Regular expression for replacing profanity words in a string


I'm trying to replace a set of words in a text string. Now I have a loop, which does not perform well:

function clearProfanity(s) {
   var profanity = ['ass', 'bottom', 'damn', 'shit'];
   for (var i=0; i < profanity.length; i++) {
      s = s.replace(profanity[i], "###!");
   }
   return s;
}

I want something that works faster, and something that will replace the bad word with a ###! mark having the same length as the original word.


Solution

  • See it working: http://jsfiddle.net/osher/ZnJ5S/3/

    Which basically is:

    var PROFANITY = ['ass','bottom','damn','shit']
      , CENZOR = ("#####################").split("").join("########")
      ;
    PROFANITY  = new RegExp( "(\\W)(" + PROFANITY.join("|") + ")(\\W)","gi");
    
    function clearProfanity(s){
        return s.replace( PROFANITY
                        , function(_,b,m,a) { 
                             return b + CENZOR.substr(0, m.length - 1) + "!" + a
                          } 
                        );
    }
    
    
    alert( clearProfanity("'ass','bottom','damn','shit'") );
    

    It would be better if the PROFANITY array would be initiated as a string, or better - directly as a Regular Expression:

    //as string
    var PROFANITY = "(\\W)(ass|bottom|damn|shit)(\\W)";
    PROFANITY = new RegExp(PROFANITY, "gi"); 
    
    //as regexp
    var PROFANITY = /(\W)(ass|bottom|damn|shit)(\W)/gi