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.
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.
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, "****");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With