I made a very simple censoring method for this. It will only track words you put into the array of bad words. I would suggest you use an advanced library for word censors.
censor.js
var censor = (function() {
function convertToAsterisk(word) {
var asteriskSentence = '';
for(var asterisks=0;asterisks<word.length;asterisks++) {
asteriskSentence+='*';
}
return asteriskSentence;
}
return function(sentence, bannedWords) {
sentence = sentence || undefined;
bannedWords = bannedWords || undefined;
if(sentence!==undefined && bannedWords!==undefined) {
for(var word=0;word<bannedWords.length;word++) {
sentence = sentence.replace(bannedWords[word], convertToAsterisk(bannedWords[word]));
}
}
return sentence;
};
})();
The method can be used like so:
var sentence = 'I like apples, grapes, and peaches. My buddy likes pears';
var bannedWords = [
'pears',
'peaches',
'grapes',
'apples'
];
sentence = censor(sentence, bannedWords);
This system does not protect bad words within other words, or tricky mispellings. Only the basics.