【问题标题】:How could I find something in an array that I know only parts of我怎么能在一个我只知道一部分的数组中找到一些东西
【发布时间】:2021-10-01 08:38:05
【问题描述】:

假设我有这两个值,我该如何匹配并查看该单词可能在数组中的所有可能组合。对于这个例子,我怎样才能在数组中找到苹果?

const fruit = ["apple", "banana", "strawberry", "grape"];
var word = "a__ple"

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你可以使用Regex来匹配部分字符串-

    const fruit = ["apple", "banana", "strawberry", "grape"];
    var regex = "^a.ple$";
    
    var result = fruit.filter(f => f.match(regex));
    console.log(result);

    【讨论】:

      【解决方案2】:

      您可以从word 创建一个正则表达式,然后使用array#filter 在数组中查找。

      const fruit = ["apple", "banana", "strawberry", "grape"],
            word = "a__ple",
            pattern = word.split("_").filter(Boolean).join('(.*?)'),
            result = fruit.filter(name => new RegExp(pattern, 'i').test(name));
      console.log(result);

      【讨论】:

        【解决方案3】:

        解决方案示例

        fruit = ["apple", "banana", "strawberry", "grape"];
        var word = "a_ple";
        
        
        const searchQuery = word.replace(/[_]/g, '.');
        const regex = new RegExp(searchQuery);
        
        for (let i = 0; i < fruit.length; i++) {
            if (regex.test(fruit[i])) {
                // Word is founded
                console.log(fruit[i]);
            }
        
        }

        但它必须使用“_”符号与丢失字符的计数相同

        另外,您可以使用带有单词的索引而不是搜索字符串我将尝试为此做另一个示例,谢谢,我希望这对您有所帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-08-24
          • 2021-09-09
          • 1970-01-01
          • 2016-02-14
          • 2011-01-31
          • 1970-01-01
          • 2011-11-23
          • 1970-01-01
          相关资源
          最近更新 更多