如何寻找一个数组jQuery中,如SQL LIKE%值%的语句 [英] How to search an array in Jquery like SQL LIKE %value% statement
问题描述
我有一些值的数组。我如何使用jquery为其匹配或值搜索该阵列接近它?
I have an array with some values. How can I search that array using jquery for a value which is matched or close to it?
var a = ["foo","fool","cool","god"];
如果我想搜索 OO
,那么它应该返回富
,傻瓜
和酷
,因为这些字符串包含 OO
。
If I want to search for oo
, then it should return foo
, fool
, and cool
because these strings contain oo
.
推荐答案
要在数组中搜索你必须使用 jQuery.grep()
或 jQuery.map()
。都返回使用一个回调函数过滤元素新的数组。
To search in the array you have to use jQuery.grep()
or jQuery.map()
. Both return new array with filtered elements using a callback function.
最快的实现(不区分大小写)中使用的indexOf
和与toUpperCase
在回调:
The fastest implementation (case insensitive) is using indexOf
and toUpperCase
in the callback:
var search_term = 'oo'; // your search term as string
var search = search_term.toUpperCase();
var array = jQuery.grep(a, function(value) {
return value.toUpperCase().indexOf(search) >= 0;
});
的如果您不需要区分大小写的搜索都可以删除 .toUpperCase()
来进一步加快速度。的
If you don't need case insensitive search you can remove both .toUpperCase()
to speed it up even further.
更灵活,但是慢得多(配不上小数组)是使用常规的前pression:
More flexible but much slower (good enough for small arrays) is to use regular expression:
var search_term = "oo"; // search term
var search = new RegExp(search_term , "i");
var arr = jQuery.grep(a, function (value) {
return search.test(value);
});
或
var search_term = "oo"; // search term
var search = new RegExp(search_term , "i");
var arr = jQuery.map(a, function (value) {
return value.match(search) ? value : null;
});
的正前pressions让你做出的搜索比%值%
要复杂得多。但是,如果你不需要它,因为它是慢很多时候不使用它。的
Regular expressions allow you to make searches much more complex than %value%
. However don't use it if you don't need it because it is many times slower.
你应该得到一个数组改编
通过匹配的元素
you should get an array arr
with the matched elements
更新:变更为例子,以避免硬codeD搜索词(根据意见的问题),并简化了code
UPDATE: Changed the examples to avoid the hardcoded search term (according to the question in comments) and simplified the code
UPDATE2:从正则表达式删除了G标记
UPDATE2: Removed the "g" flag from the regex
这篇关于如何寻找一个数组jQuery中,如SQL LIKE%值%的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!