Reputation: 869
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");
}
});
I'm sure my if statement is wrong...please help me out!
Upvotes: 0
Views: 552
Reputation: 168416
Instead of searching for the words in an array just create a regular expression to replace them:
$("#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