如果输入包含数组的任何单词 [英] if input contains any word in array
本文介绍了如果输入包含数组的任何单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个输入,我想知道是否有在我的数组中的值的存在。举个简单的例子我的阵列
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"];
我已经想通了如何触发它,如果我例如键入简单的'太阳',但我想知道如果'hhsun'或'sunee存在过。
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));
}
});
推荐答案
检查是否 _array
的元素是文本框的文本字符串:
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');
演示: http://jsfiddle.net/WLacb/3/
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');
}
演示: http://jsfiddle.net/WLacb/9/
Demo: http://jsfiddle.net/WLacb/9/
这篇关于如果输入包含数组的任何单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文