用于替换字符串中的亵渎词的正则表达式

时间:2011-03-12 11:42:40

标签: javascript profanity

我正在尝试替换文本字符串中的一组单词。现在我有一个循环,但表现不佳:

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

我想要一些效果更快的东西,以及用###!标记替换坏字的东西,其长度与原始字相同。

2 个答案:

答案 0 :(得分:4)

这是一种方法:

String.prototype.repeat = function(n){
    var str = '';
    while (n--){
        str+=this;
    }
    return str;
}

var re = /ass|bottom|damn|shit/gi
  , profane = 'my ass is @ the bottom of the sea, so shit \'nd damn';

alert(profane.replace(re,function(a) {return '#'.repeat(a.length)}));
//=>my ### is @ the ###### of the sea, so #### 'n ####

完成:这是一种更简单的方法,将字边界考虑在内:

var re = /\W+(ass|shit|bottom|damn)\W+/gi
      , profane = [ 'My cassette of forks is at the bottom'
                   ,'of the sea, so I will be eating my shitake'
                   ,'whith a knife, which can be quite damnable'
                   ,'ambassador. So please don\'t harrass me!'
                   ,'By the way, did you see the typo'
                   ,'in "we are sleepy [ass] bears"?']
                  .join(' ')
                  .replace( re, 
                              function(a){ 
                                return a.replace(/[a-z]/gi,'#'); 
                              } 
                   );
alert(profane);

答案 1 :(得分:3)

看到它起作用: http://jsfiddle.net/osher/ZnJ5S/3/

主要是:

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'") );

如果将PROFANITY数组作为字符串启动,或者更好 - 直接作为正则表达式,那会更好:

//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