我不知道如何做到这一点。我正在使用 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");
}
});
我确信我的 if 语句是错误的...请帮助我!
最佳答案
不必在数组中搜索单词,只需创建一个正则表达式来替换它们:
$("#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");
}
});
关于javascript 检查输入是否有任何值在禁止单词数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20808639/