if input contains any word in array

♀尐吖头ヾ 提交于 2019-12-24 03:18:10

问题


I have an input and I want to know if any of the values in my array exist. For a simple example my array is

var _array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

I've figured out how to trigger it if I type simply 'sun' for example, but I want to know if 'hhsun' or 'sunee' exist too.

$('input').keyup(function() {
    var _val = $(this).val();
    $('p').text(_val);

    var _array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

    if (_array.indexOf(_val) != -1) {
        $('span').text('it worked');
    } else {
        $('span').text(_array.indexOf(_val));
    } 
});

fiddle


回答1:


Check to see if an element of _array is a substring of the textbox's text:

var _array = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];

for (var i = 0; i < _array.length; i++) {
    if (_val.indexOf(_array[i]) != -1) {
        $('span').text('it worked');
        return;
    }
}

$('span').text('nothing');

Demo: http://jsfiddle.net/WLacb/3/


A slightly more obscure solution would be with regex:

if (/sun|mon|tue|wed|thu|fri|sat/ig.test(_val)) {
    $('span').text('it worked');
} else {
    $('span').text('nothing');
}

Demo: http://jsfiddle.net/WLacb/9/




回答2:


A simple way to do this is to use the built in jquery.each command to loop through each element of the array and check if it is in the textbox value.

http://jsfiddle.net/WLacb/10/

$('span').text(-1);
$.each(_array, function(key, value) {
    if (_val.indexOf(value) != -1) {
        $('span').text('it worked');
    }
});


来源:https://stackoverflow.com/questions/11965183/if-input-contains-any-word-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!