如果任何值在禁止字的数组中,则从输入中检查javascript

时间:2013-12-27 22:26:53

标签: javascript jquery arrays

我无法弄清楚如何做到这一点。我正在使用jQuery,我知道inArray函数,但我被卡住了。当用户在输入字段中插入一些值时,我想检查输入的任何单词是否在数组中......如果他们要删除它们。这就是我所拥有的:

<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

我确定我的if语句是错的......请帮帮我!

2 个答案:

答案 0 :(得分:1)

您切换了检查并在inArray参数中搜索。检查api,它表示使用inArray(value, array)(不是数组,值)。

答案 1 :(得分:1)

不是搜索数组中的单词,而是创建一个正则表达式来替换它们:

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");
}
});