0

I'm trying to write a function that uses a regex to filter an array of names and returns a new array that contains only those individuals with a given last name. The issue is that it will only return one instance. I feel it's likely due to the regEx - can anyone help?

function getSmith(arr) {
  const regex = /Smith$\b/g;
  return arr.filter(name => regex.test(name));
}

console.log(
  getSmith(['John Smith', 'Chris Smith'])
)  
mplungjan
  • 169,008
  • 28
  • 173
  • 236
David Clark
  • 142
  • 8
  • It could be like this `return arr.filter(name => /\bSmith$/.test(name));` – The fourth bird Dec 19 '21 at 11:33
  • @Thefourthbird It could but I would rather have the regex pattern defined separately. – David Clark Dec 19 '21 at 11:34
  • See the duplicate for the reason of that behaviour. – The fourth bird Dec 19 '21 at 11:35
  • 2
    Remove the `g` flag from your expression (see the [linked question](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results) for why). Separately, having `\b` after `$` doesn't make any sense, without the `m` flag `$` means "end of input" and so by definition is a word break. You might want a word break in *front* of `Smith` as @Thefourthbird suggested, though (it depends on whether you want `"John Stringsmith"` to match), and I'd use a case-insensitive match. So `const regex = /\bsmith$/i;`. – T.J. Crowder Dec 19 '21 at 11:36
  • 1
    `arr.filter(name => name.toLowerCase().includes("smith"));` is likely a simpler filter to understand – mplungjan Dec 19 '21 at 11:36

0 Answers0