BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11663

scanning a sentence for prohibited words

Using a Stackoverflow answer to this question, I did this to check if any words in a message exist in an array of prohibited words

if ($.inArray(message, badwordsarray) !== -1){
   console.log("bad word found")
}

This works in the following example

var message = "blah"
var badwordsarray = ["blah", "foo", "baz"]
  if ($.inArray(message, badwordsarray) !== -1){
       console.log("bad word found")
    }

However, if the message is longer than 1 one and contains spaces, it doesn't detect the bad words. In this example, the bad word isn't detected because of the inclusion of happy

    var message = "happy blah"
    var badwordsarray = ["blah", "foo", "baz"]
      if ($.inArray(message, badwordsarray) !== -1){
           console.log("bad word found")
        }

What is the best way to scan a sentence for prohibited words in Javascript?

Upvotes: 0

Views: 216

Answers (3)

Matthew Dunbar
Matthew Dunbar

Reputation: 426

Another option is to create a for loop and iterate over each of the bad words.

var message = "happy blah"
var badwordsarray = ["blah", "foo", "baz"]

for(var i = 0; i < badwordsarray.length; i++) {
    if(message.indexOf(badwordsarray[i]) !== -1) {
        alert('bad word found');
        // You could also set a boolean variable to true when a word is found
    }
}

Upvotes: 0

Will
Will

Reputation: 4155

You'll need to tokenize the message string.

var message = "happy blah";
var badwordsarray = ["blah", "foo", "baz"];
var messageParts = message.split(" ");
$(messageParts).each(function(i, item){
    if ($.inArray(item, badwordsarray) !== -1) {
        console.log("bad word found:", item);
    }
});

http://jsfiddle.net/udd5k8j3/

Upvotes: 3

axelduch
axelduch

Reputation: 10849

RegExp to the rescue!

var message = "happy blah";
var badwordsarray = ["blah", "foo", "baz"];

var containsBadWord = badwordsarray.some(function (word) {
    return new RegExp('\\b' + word  + '\\b').test(word);
});

if (containsBadWord) {
    console.log("bad word found");
}

Upvotes: 0

Related Questions