denikov
denikov

Reputation: 869

javascript check from input if any values are in array of forbidden words

I'm having trouble figuring out how to do this. I'm using jQuery and I know the inArray function but I'm stuck. When the user inserts some values in an input field, I want to check if any of the words entered are in an array...if they are then to remove them. Here's what I have:

<input type="text" id="search"/>

$("#search").bind('enterKey', function(e){
  var search = $('#search').val();
  var check = ['on', 'a', 'the', 'of', 'in', 'if', 'an'];
  var id = $.inArray(check, search);
  if (id !== -1){
    alert ("in array");
  }else{
    alert ("not in array");
  }
});
$('#search').keyup(function(e){
  if(e.keyCode == 13){
    $(this).trigger("enterKey");
  }
});

Fiddle

I'm sure my if statement is wrong...please help me out!

Upvotes: 0

Views: 552

Answers (2)

MT0
MT0

Reputation: 168416

Instead of searching for the words in an array just create a regular expression to replace them:

JSFIDDLE

$("#search").bind('enterKey', function(e){
    var search = $('#search').val(),
        check = ['on', 'a', 'the', 'of', 'in', 'if', 'an'],
        regexp = new RegExp( '\\b' + check.join( '\\b|\\b' ) + '\\b', 'ig' );
    alert( search.replace( regexp, '' ) );
});
$('#search').keyup(function(e){
if(e.keyCode == 13)
{
  $(this).trigger("enterKey");
}
});

Upvotes: 1

Tomanow
Tomanow

Reputation: 7377

You switched check and search in the inArray parameters. Check the api, it indicates use inArray(value, array) (not array, value).

Upvotes: 1

Related Questions