5

elmid = "R125";

switch(true){

    case elmid.match(/R125/):
      idType = "reply";
    break;

}

alert(idType);  // Returns undefined

-------------------BUT----------------------

elmid = "R125";

if (elmid.match(/R125/)){idType = "reply";}

alert(idType);  // Returns "reply"


Using the swtich returns undefined but using an if returns the expected value, what is causeing the switch to fail ? Why is this the case? what am i doing wrong here? can any one explain why I get different results =).

NOTE: No advices to use an if statement in this case I know that, my question concise for asking there hence there is not only 1 case in the switch statement.

3 Answers 3

11
elmid.match(/R125/)

This returns the actual regex matches, not true or false.

When you're writing an if statement and using ==, some basic type conversion can be performed so that it works as expected. Switch statements use the identity comparison (===), and so this won't work.

If you want to do it this way, use regex.test() (which returns a boolean) instead.

case /R125/.test(elmid):
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for clearing that up for me =) ... I am just waiting for this stupid timer saying "You can accept an answer in 2 minutes" :P
0

.match returns the matches that matched the RegEx, not just true or false.
In a switch statement, the test values are compared using ===, not ==.
So the resulting expression ["R125"] === true is not true and the case never executed.

Comments

0

The match function returns an array or null, so it will never return "true". But you are passing true into the switch statement, so all you are able to check against is "true". See the match() defintion

Match Definition

But if you are using an if statement (with the == operator instead the === operator), also the found array will be valid as true in the if statement.

Comments

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.