Reputation: 149
I was wondering why the result of my regular expression wasn't going to the case I wanted to go through.
var r = "This is a test.";
var ex = /a/g;
var l = ex.exec(r);
alert(l);
switch (l)
{
case "a":
alert("good");
break;
default:
alert("error");
}
If you run this, you can see that "l" does in fact does equal "a" which then should trigger the case function. If anyone knows why it isn't, please help. Thank you
Upvotes: 1
Views: 75
Reputation: 889
@LoganMacMonkey, the type return by var l = ex.exec(r); is array. Refer this and you try to compare array with string using switch case structure. Due to this reason your code is not working
To resolve it Convert
switch (l)
To the,
switch(l.toString())
Hope it you are looking for the same!! :)
Upvotes: 0
Reputation: 1656
In regular expressions you have matches, To check the matches that your regex is generating use console.log, the devtool built-in debugger or pages like https://regex101.com/
Upvotes: 0
Reputation: 370979
Test against l[0]
instead to get the matched substring:
var r = "This is a test.";
var ex = /a/g;
var l = ex.exec(r);
switch (l[0])
{
case "a":
alert("good");
break;
default:
alert("error");
}
Upvotes: 3