1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
function filterString(string, wordsList, replace){
var string = string.trim();
var string = string.replace( /\s\s+/g, ' ' ); // remove more than one space
var splStr = string.split(' ');
var isTrue = [] // There is no error
var badWord = [] // store bad words here
var result; // final result true OR false
var replace = []; // list items to replace the bad word
$.each(splStr, function( index, value ) {
//console.log( index + ": " + value );
checkBad = $.inArray( value, wordsList );
//console.log(checkBad);
// if found
if(checkBad > -1){
isTrue.push(1); // there is an error
//console.log(splStr[index]+' is bad');
badWord.push(splStr[index]);
} else {
isTrue.push(0);
//console.log(splStr[index]+' is good');
}
//console.log(badWord);
}); // end each
var checkErrors = $.inArray( 1, isTrue );
if(checkErrors > -1){
result = true;
var sortBadWords = jQuery.uniqueSort( badWord );
//console.log('List '+sortBadWords);
} else {
var result = false;
var sortBadWords = null;
}
return [result, sortBadWords, isTrue];
}
var wordsList = ['fuck', 'suck'];
var replace = ['', '***']; // replace with nothing or with stars
$('.wrap').on('keyup', function(){
var value = $(this).val();
badList = filterString(value, wordsList, replace);
//console.log(badList);
if((badList[0]) === true){
console.log('is true?: '+badList[0]);
console.log('list words '+badList[1]);
console.log(badList[1]);
var countWords = badList[1].length;
console.log('There are ' +countWords+ ' word');
var indexWords = countWords-1;
for ( var i=0; i<=indexWords; i++ ){
console.log('x '+badList[1][i]);
var regex = new RegExp(badList[1][i], 'g');
var newW = value.replace(regex, '***');
//console.log('newW '+newW);
}
} else {
console.log('is true?: '+badList[0]);
var newW = value;
}
console.log('true array '+badList[2]);
if(badList[0]){
console.log('There are some bad words');
console.log('first word: '+badList[1][0]);
console.log('second word '+badList[1][1]);
console.log('combine words '+badList[1].join(','));
} else {
console.log('Safe string :\)');
}
$('.prev').html(newW).show();
}); |
Partager