简体   繁体   中英

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'.

This is in javascript.

Use indexOf as @Annie suggested. indexOf is used for finding substrings inside a given string. If there's no match, it returns -1 , otherwise it returns the starting index of the first match. If that index is 0 , it means the match was in the beginning.

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. 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.

Loop through each string in the input array, and collect all strings that match (using either indexOf or a regex) in a new array. 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!


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.

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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