我正在尝试替换文本字符串中的一组单词。现在我有了一个循环,它的性能不是很好:
function clearProfanity(s) {
var profanity = ['ass', 'bottom', 'damn', 'shit'];
for (var i=0; i < profanity.length; i++) {
s = s.replace(profanity[i], "###!");
}
return s;
}我想要的东西是更快的工作,并与具有相同长度的原始单词具有相同长度的###!标记替换坏单词。
发布于 2011-03-12 19:45:35
看着它工作: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发布于 2011-03-12 19:52:06
这里有一种方法:
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);https://stackoverflow.com/questions/5282270
复制相似问题