如何在Jquery中搜索数组,如SQL LIKE值%语句

时间:2013-08-28 13:28:30

标签: javascript jquery regex

我有一个带有一些值的数组。如何使用jQuery搜索该数组以获得与其匹配或接近的值?

var a = ["foo","fool","cool","god","acl"];

如果我想搜索c,则应该返回cool而不是acl

我如何实现这一目标?

5 个答案:

答案 0 :(得分:1)

试试这个: -

arr = jQuery.grep(a, function (value) {
    search = /c/gi;
    if(value.match(search)) return true;
        return false;
    });

function find(arr) {
    var result = [];

    for (var i in arr) {
        if (arr[i].match(/c/)) {
            result.push(arr[i]);
        }
    }

    return result;
}

window.onload = function() {
    console.log(find(["foo","fool","cool","god","acl"]));
};

答案 1 :(得分:1)

使用substring检查数组中的每个字符串是否以您要搜索的字符串开头:

var strings = [ "foo", "cool", "acl" ];
var needle = "c";

for (var i = 0; i < strings.length; ++i) {
    if (strings[i].substring(0, needle.length) === needle) {
        alert("found: " + strings[i]);
    }
}

答案 2 :(得分:1)

一种简单的方法是检查以'c'开头的单词并迭代数组。

var ar = ['acl','cool','cat']
for(var i = 0 ; i<ar.length ; i++){
   console.log(ar[i].match(/^c/))
}
//Prints:
//null
//["c", index: 0, input: "cool"]
//["c", index: 0, input: "cat"]

答案 3 :(得分:1)

您可以使用自JavaScript 1.6以来可用的过滤方法。它会返回一个包含过滤值的数组。如果你想匹配多个项目,非常方便。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

var a = ["foo","fool","cool","god","acl"];
var startsWith = 'c';

a.filter(function (value) {
    return value && value.length > 0 && value[0] == startsWith;
});

// yields: ["cool"]

答案 4 :(得分:0)

var a = ["foo","fool","cool","god","acl"];
var Character="f";
for(i=0;i<a.length;i++){
    if(a[i].indexOf(Character)!=-1){

        document.write(a[i]+"<br/>");
    }
 }