简体   繁体   English

从 javascript 数组中查找匹配的字符串

[英]Finding matching string from javascript array

I have one array of strings.我有一个字符串数组。 I need to find all strings starting with a key.我需要找到所有以键开头的字符串。 for eg: if there is an array ['apple','ape','open','soap'] when searched with a key 'ap' i should get 'apple' and 'ape' only and not 'soap'.例如:如果有一个数组['apple','ape','open','soap']当使用键 'ap' 进行搜索时,我应该只得到 'apple' 和 'ape' 而不是 'soap'。

This is in javascript.这是在javascript中。

Use indexOf as @Annie suggested. 使用indexOf作为@Annie建议。 indexOf is used for finding substrings inside a given string. indexOf用于查找给定字符串中的子字符串。 If there's no match, it returns -1 , otherwise it returns the starting index of the first match. 如果没有匹配,则返回-1 ,否则返回第一个匹配的起始索引。 If that index is 0 , it means the match was in the beginning. 如果该索引为0 ,则表示匹配在开头。

One other way is to use regular expressions . 另一种方法是使用正则表达式 Use the ^ character to match from the beginning of the string. 使用^字符从字符串的开头匹配。 The regular expression: 正则表达式:

/^he/

will match all strings that begin with "he" , such as "hello", "hear", "helium", etc. The test method for RegExp returns a boolean value indicating whether or not there was a successful match. 将匹配以"he"开头的所有字符串,例如“hello”,“hear”,“helium”等.RegExp的test方法返回一个布尔值,指示是否存在成功匹配。 The above regex can be tested as /^he/.test("helix") which will return true, while /^he/.test("sheet") will not as "he" doesn't appear in the beginning. 上面的正则表达式可以测试为/^he/.test("helix") ,它将返回true,而/^he/.test("sheet")将不会因为"he"没有出现在开头。

Loop through each string in the input array, and collect all strings that match (using either indexOf or a regex) in a new array. 遍历输入数组中的每个字符串,并收集新数组中匹配的所有字符串(使用indexOf或regex)。 That new array should contain what you want. 那个新数组应该包含你想要的东西。

function find(key, array) {
  // The variable results needs var in this case (without 'var' a global variable is created)
  var results = [];
  for (var i = 0; i < array.length; i++) {
    if (array[i].indexOf(key) == 0) {
      results.push(array[i]);
    }
  }
  return results;
}

With 2 improvements , can find if contains, not only as first char, and it has a third parameter to define the returned value : true means return just the number of element inside the array (index/key), false or anything not accepted or no value means return the complete string array[element], and if set to 'position=3', return the values of array which contains the string exactly in the ' after = number' position, here 3! 通过2次改进 ,可以找到if包含,不仅作为第一个char,还有第三个参数来定义返回值:true表示只返回数组中的元素数(索引/键),false或任何未接受的或没有值意味着返回完整的字符串数组[element],如果设置为'position = 3',则返回包含完全位于'after = number'位置的字符串的数组的值,此处为3!


function find(key, array, returnindex)
{
var results = [];
if {returnindex.indexOf('position=') == 0}
{
    var a = parseInt(returnindex.replace('position=',''));
    returnindex = false;
}
else if (returnindex != true)
{
    returnindex = false;
}
for (var i = 0; i < array.length; i++)
{
    var j = '-'+array[i].indexOf(key);
    if (typeof a == 'undefined')
    {
        if (i > 0)
        {
            j = 'ok';
        }
    }
    else
    {
        if (i == a+1)
        {
            j = 'ok';
        }
    }
    if (j == 'ok' && returnindex)
    {
        results.push(i);
    }
    else
    {
        results.push(array[i]);
    }
}
return results;
}

All these methods would only work to find the exact match on the string in the array for the case scenario of the array having multiple words with space in the string.所有这些方法仅适用于在数组中包含多个单词且字符串中有空格的情况下找到数组中字符串的完全匹配。 any idea why is that?知道为什么吗?

for the the given scenario above, we have to use the string.includes(substring) method to find the entire string in the array.对于上面给定的场景,我们必须使用string.includes(substring)方法来查找数组中的整个字符串。

You can use filter with regex to accomplish this: 您可以使用带有正则表达式的过滤器来完成此任务:

 function startsWith(array, key) { const matcher = new RegExp(`^${key}`, 'g'); return array.filter(word => word.match(matcher)); } const words = ['apple','ape','open','soap'] const key = 'ap' const result = startsWith(words, key) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM