Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I do a jQuery swear word / bad word filter?

Tags:

jquery

I know there are many arguments as to why this is a bad idea, but in my implementation I'm planning on enabling/disabling bad words in the account settings. In other words, bad words will be visible by default, but switched off / hidden if asked.

The plan will be to send a JSON string to the client and let the client filter out the bad words.

json string

['swear1', 'swear2']

original phrase

this phrase includes swear1

final output

this phrase includes ****

this is what I've tried so far

    $(document).ready (function () {
        $('body').html().replace('asdf', 'ffff');
    });

now on a side note, I am using asp.net mvc and I "could" do this on the server side, but I was thinking that this would be better if offloaded to the client... I'm open to suggestions on this.

like image 660
Chase Florell Avatar asked Dec 27 '10 18:12

Chase Florell


2 Answers

Something like this might work:

String.prototype.repeat = function(num){
  return new Array(num + 1).join(this);
}

var filter = ['ass', 'piss'];

$('.post').text(function(i, txt){

  // iterate over all words
  for(var i=0; i<filter.length; i++){

    // Create a regular expression and make it global
    var pattern = new RegExp('\\b' + filter[i] + '\\b', 'g');

    // Create a new string filled with '*'
    var replacement = '*'.repeat(filter[i].length);

    txt = txt.replace(pattern, replacement);
  }

  // returning txt will set the new text value for the current element
  return txt;
});

Working example on jsFiddle

Edit: Added boundaries so it won't replace words that contain the swear words. I've used double backslashes because backslashes should be escaped in a string, see this topic.

like image 71
Harmen Avatar answered Sep 17 '22 04:09

Harmen


Here is a lightweight function.

var filterWords = ["fool", "dumb", "shit", "ass", "couch potato"];
var rgx = new RegExp(filterWords.join("|"), "gi");
function wordFilter(str) {           
    return str.replace(rgx, "****");            
}
like image 22
angry kiwi Avatar answered Sep 17 '22 04:09

angry kiwi