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?

3
  • 2
    Make the regular expressions check the entire input by using the anchors ^ and $ Commented May 27, 2020 at 12:52
  • 1
    Does this answer your question? Match whole string Commented May 27, 2020 at 12:54
  • This might be a highly simplified example; if not, you could also just use includes for simplicity: illegals.contains(testTxt); Commented May 27, 2020 at 12:54

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

ahh ok, I was missing the stupid anchors, duh, need more coffee, thanks!
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. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.