0

Currently I have this:

const illegals = [/Foo/, /Bar/, /FooBar/];
var testTxt = "Foo Fighter";
var isMatch = illegals.some(rx => rx.test(testTxt));

and since the testTxt contains 'Foo' it returns true. But I only want to match if it matches the full text (i.e. 'Foo Fighter') otherwise return false. What have I got wrong here?

snappymcsnap
  • 2,050
  • 2
  • 29
  • 53
  • 2
    Make the regular expressions check the entire input by using the anchors `^` and `$` – VLAZ May 27 '20 at 12:52
  • 1
    Does this answer your question? [Match whole string](https://stackoverflow.com/questions/6298566/match-whole-string) – VLAZ May 27 '20 at 12:54
  • This might be a highly simplified example; if not, you could also just use [`includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) for simplicity: `illegals.contains(testTxt);` – esqew May 27 '20 at 12:54

1 Answers1

4

Like Vlaz already put in his comment, you need to include ^and $ before and after your pattern to signal that you want to match the whole string.

const illegals = [/^Foo$/, /^Bar$/, /^FooBar$/];
var testTxt = "Foo Fighter";
console.log(illegals.some(rx => rx.test(testTxt)))     // false
console.log(illegals.some(rx => rx.test('Bar')))       // true
console.log(illegals.some(rx => rx.test('Bar stool'))) // false
console.log(illegals.some(rx => rx.test('FooBar')))    // true
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • ahh ok, I was missing the stupid anchors, duh, need more coffee, thanks! – snappymcsnap May 27 '20 at 13:00
  • Wow, I honestly don't get it! :-) How does this _simplest of all answers_ suddenly get 4 upvotes, when some of my other answers where I found myself researching and working on for hours don't even get a single one?!? :D :D :D - Well, I guess these "reputation" points mustn't be taken too seriously. ;-) – Carsten Massmann May 27 '20 at 16:46