almostamachine
almostamachine

Reputation: 161

RegEx as a conditional in a if else statement returns unexpected result

I want to pass a argument to a function, and check if the argument consists of one or two letters or numbers. If they are, evaluate to true, if they aren't, evaluate to false.

The arguments that has to evaluate to true are 'PP', 'P', 'M', 'G', 'GG', 'XS', 'S', 'L', 'XL' and a range of numbers from '30' to '50', but there maybe more. What they have in common: they never have more than 2 characters, so I came up with this regular expression, but I'm not sure if this is 100%.

/^[0-9]{1,2}$/gi.test('09');   // returns 'true'
/^[a-z]{1,2}$/gi.test('AZ');   // returns 'true'
/^[0-9]{1,2}$/gi.test('Word'); // returns 'false'
/^[a-z]{1,2}$/gi.test('Word'); // returns 'false'

On their own, they work just fine. But when I use it in a if...else statement, I don't get the expected result:

function example(value) {
  if (value === /^[0-9]{1,2}$/gi.test(value) || /^[a-z]{1,2}$/gi.test(value) ) {
    // do stuff...
  } else {
    // do other stuff...
  }
}

example('AA');   // returns 'true'
example('99');   // returns 'false', expected 'true'
example('Word'); // returns 'false'

What I'm getting wrong? Also, how can I improve this code?

Upvotes: 0

Views: 46

Answers (1)

Matt
Matt

Reputation: 3760

Your logic is incorrect. In your if statement you are testing:

value === /^[0-9]{1,2}$/gi.test(value)

Which is equivalent to:

'99' === /^[0-9]{1,2}$/gi.test('99')

Which is equivalent to:

'99' === true

Which is false.

You just need to take out the value === part.

Upvotes: 2

Related Questions