【问题标题】:How can I search a string from a string array in javascript?如何从 javascript 中的字符串数组中搜索字符串?
【发布时间】:2013-04-21 18:18:21
【问题描述】:

我有一个字符串 'a' 并且想要所有具有 'a' 字符串数组的结果。

var searchquery = 'a';
var list = [temple,animal,game,match, add];

我想要 result = [animal,game,match,add]; 所有名称中包含 'a' 的元素。我该如何实现?

【问题讨论】:

  • 对于这个简单的问题,使用 regex 会有点过头了..

标签: javascript regex search


【解决方案1】:
<div id="display"></div>

var searchquery = 'a';
var list = ["temple", "animal", "game", "match", "add"];
var results = list.filter(function(item) {
    return item.indexOf(searchquery) >= 0;
});

document.getElementById("display").textContent = results.toString();

jsfiddle

【讨论】:

    【解决方案2】:

    您可以filter列表:

    var searchquery = 'a';
    var list = ['temple', 'animal', 'game', 'match', 'add'];
    var results = list.filter(function(item) {
        return item.indexOf(searchquery) >= 0;
    });
    // results will be ['animal', 'game', 'match', 'add']
    

    (请注意,您需要将list数组中的字符串引用。)

    【讨论】:

    • 快! :) 摆弄需要额外的时间:P
    • @pandit - 我认为正则表达式不会在性能或代码清晰度方面为您带来任何好处。由于searchquery 是一个变量,我认为恰恰相反。此外,我还添加了指向 filter 函数文档的链接。
    猜你喜欢
    • 2011-07-22
    • 2022-01-23
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多