-1

I want to select some words out of an array of words. For example, the array is like below:

var list = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry']

I use below script to perform selection

var pattern = "Der";
var matched = list.filter(a => a.indexOf(pattern) >= 0);

The matched variable will contains:

['Dermatologist']

But when I change the pattern variable value to "ist" the result would be

['Dermatologist','Specialist']

I want my filtering to works only matching from the beginning of every word. So if I set pattern variable value to "Bro" it will returns

['Brothers','Browsers']

But when I set pattern variable value to "ers" it will returns empty array

[]

Can anybody help?

Bromo Programmer
  • 670
  • 2
  • 13
  • 37
  • It's not clear exactly what you want. Maybe you need `startsWith` or `endsWith` methods on String. – Tushar Aug 21 '19 at 11:59

2 Answers2

0

You can use a regex with ^ (which means beginning of line) before the pattern:

var list = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry'];

var pattern = /^Bro.*/;

var matched = list.filter(a => pattern.test(a));

console.log(matched);
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

You can simply use startsWith

var list = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry']

var pattern = "Der";
var matched = list.filter(a => a.startsWith(pattern));

console.log(matched)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60