Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
Wind Chimez Avatar asked Jun 19 '10 07:06

Wind Chimez


2 Answers

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)
like image 82
dean Avatar answered Oct 01 '22 19:10

dean


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.

like image 26
Anurag Avatar answered Oct 01 '22 20:10

Anurag