Compare array of words to a textarea input with ja

2020-03-30 09:43发布

I have a textarea inside a form.

Before the form is submitted, the textarea is validated and checked so it is not empty, not over 2000 characters, not contain forbidden characters etc...

I am working on the last part of the validation, which would need the textarea to be compared to an array of "bad words".

This to help me maintain and keep a good "language" on my site.

I am not very good on js, so does anybody know of a way to compare each word of the textarea to the array of bad words?

Also, would this slow down the validation much? (the array contains at most 100 words).

Thanks

5条回答
甜甜的少女心
2楼-- · 2020-03-30 10:04

This code replaces bad words with *****

// creating regex
var words = ['bad', 'words'];
var wordsStr = "";
for(var i=0; i<words.length; i++) {
    wordsStr += words[i];
    if (i < words.length -1) {
        wordsStr += "|";
    }
}
// wordsStr is "bad|words"
var regex = new RegExp(wordsStr, "gi"); // g: replace all; i:insensitive

// replacing
var text = "I cant say bad words!";
text = text.replace(regex, "****");
// text is "I cant say **** ****!"

See in jsfiddle

查看更多
别忘想泡老子
3楼-- · 2020-03-30 10:09
var bad_words = new Array('word1', 'word2');
var user_words = document.getElementById('textarea').split(/\W+/);

for( var i in bad_words)
{
  if( user_words.indexOf( bad_words[i] ) != -1 )
  {
    alert( 'The textarea has bad word!');
    break;
  }
}
查看更多
欢心
4楼-- · 2020-03-30 10:11

If you wanted to check for the presence of "expletive1" and "expletive2" you'd do the following:

my_textarea = document.getElementById('textarea_id');

if (/\b(?=\w)(expletive1|expletive2)\b(?!\w)/i.test(my_textarea.value)) {
    // we found bad words!  do something
} else {
    // no bad words found, carry on, nothing to see here
}

And you'd just add more words to the list in the same manner (expletive1|expletive2|expletive3|expletive4)

Keep in mind that to keep the words out of your app entirely you'll also need to do server-side filtering.

查看更多
Rolldiameter
5楼-- · 2020-03-30 10:13
var bad_words = ['stupid', 'dang']; // watered down
for (var i = 0; i <= bad_words.length; i++) {
    if (document.getElementById('my_textarea').value.match(bad_words[i])) {
        // has bad word!
    }
}

This will keep your code a bit neater, because you don't have to have 100 words in one regex match.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-03-30 10:19

You can downvote me if you want, but maybe just don't make the clbuttic mistake of trying to filter in the first place :D

查看更多
登录 后发表回答