Finding matching string from javascript array

前端 未结 4 1337
失恋的感觉
失恋的感觉 2021-02-08 07:29

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

4条回答
  •  醉酒成梦
    2021-02-08 08:02

    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)

提交回复
热议问题