Don*_*Joy 4 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;
}
Run Code Online (Sandbox Code Playgroud)
我想要一些工作更快的东西,并且可以用与###!原始单词长度相同的标记替换坏词。
这是一种方法:
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 ####
Run Code Online (Sandbox Code Playgroud)
完整说明:这是一种更简单的方法,将单词边界考虑在内:
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);
Run Code Online (Sandbox Code Playgroud)
查看它的工作原理: 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'") );
Run Code Online (Sandbox Code Playgroud)
如果数组作为字符串启动会更好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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4306 次 |
| 最近记录: |