首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于替换字符串中脏话的正则表达式

用于替换字符串中脏话的正则表达式
EN

Stack Overflow用户
提问于 2011-03-12 19:42:40
回答 2查看 4.4K关注 0票数 4

我正在尝试替换文本字符串中的一组单词。现在我有了一个循环,它的性能不是很好:

代码语言:javascript
复制
function clearProfanity(s) {
   var profanity = ['ass', 'bottom', 'damn', 'shit'];
   for (var i=0; i < profanity.length; i++) {
      s = s.replace(profanity[i], "###!");
   }
   return s;
}

我想要的东西是更快的工作,并与具有相同长度的原始单词具有相同长度的###!标记替换坏单词。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-12 19:45:35

看着它工作:http://jsfiddle.net/osher/ZnJ5S/3/

这基本上就是:

代码语言:javascript
复制
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数组作为字符串初始化,或者更好地-直接作为正则表达式初始化:

代码语言:javascript
复制
//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
票数 4
EN

Stack Overflow用户

发布于 2011-03-12 19:52:06

这里有一种方法:

代码语言:javascript
复制
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 ####

要做到完整:这里有一个更简单的方法,考虑到单词的边界:

代码语言:javascript
复制
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);
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5282270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档