以下是一種方法:
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);
嘿,「底部」是褻瀆? – kennytm 2011-03-12 11:46:23
我試圖成爲溫柔的...... – 2011-03-12 11:52:31
+1,我喜歡代碼很有趣 – smartcaveman 2011-03-12 11:54:39