snappymcsnap
snappymcsnap

Reputation: 2103

Regex match against array of values

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?

Upvotes: 0

Views: 52

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

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

Upvotes: 4

Related Questions