2011-03-12 70 views
4

我试图用文本字符串替换一组单词。现在我有一个循环,不执行得好:替换字符串中的亵渎词的正则表达式

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

我想要的东西,工作速度更快,并且东西,这将与具有相同长度的原词###!马克更换坏词。

+4

嘿,“底部”是亵渎? – kennytm 2011-03-12 11:46:23

+0

我试图成为温柔的...... – 2011-03-12 11:52:31

+0

+1,我喜欢代码很有趣 – smartcaveman 2011-03-12 11:54:39

回答

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 
+0

感谢您的所有解释! – 2011-03-12 12:02:30

+0

@ Don-Joy @Radagast the Brown - 那么发生了什么“无偏见”?这实在太简单了。正则表达式确实需要寻找单词边界。 – Pointy 2011-03-12 12:04:29

+0

是的,它很简单,但它不是一个亵渎引擎,它是一个简单的客户端JS功能,掩盖了我的背后。这对我来说已经够好了。 – 2011-03-12 12:17:14

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); 
+0

谢谢单词边界处理。但是,请注意,从预先准备的预先提取的字符串中切割比循环中的字符串更好,这是针对您希望替换的每个事件完成的。 – 2016-06-15 11:01:31