Вот один из способов сделать это:
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);