Regular expression to replace profanity words in a string

I am trying to replace a set of words in a text string. Now I have a loop that doesn't work well:

function clearProfanity(s) { var profanity = ['ass', 'bottom', 'damn', 'shit']; for (var i=0; i < profanity.length; i++) { s = s.replace(profanity[i], "###!"); } return s; } 

I want something that works faster, and something that replaces the bad word with the ###! sign ###! having the same length as the original word.

+4
source share
2 answers

See how it works: http://jsfiddle.net/osher/ZnJ5S/3/

Mainly:

 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'") ); 

It would be better if the PROFANITY array was initiated as a string, or better directly as a regular expression:

 //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 
+3
source

Here is one way to do this:

 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 #### 

To be complete: here is an easier way to do this, taking into account word boundaries:

 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(/[az]/gi,'#'); } ); alert(profane); 
+4
source

Source: https://habr.com/ru/post/1343433/


All Articles