The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String. equals method; consequently, the comparison of String objects in switch statements is case sensitive.
JavaScript actually allows the cases to be any object so Regular Expressions there are perfectly valid (unlike in many other languages where what you can use as the case is more limited). It may be “valid”, but it doesn't appear to actually work (at least not in Firefox, anyway).
The -Regex parameter allows switch statements to perform regular expression matching against conditions. Output: One or more non-digits Any single char. Anchors and one or more word chars.
In addition to if...else , JavaScript has a feature known as a switch statement. switch is a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases.
You can't do it in a (This isn't quite true, as Sean points out in the comments. See note at the end.)switch
unless you're doing full string matching; that's doing substring matching.
If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:
switch (base_url_string) {
case "xxx.local":
// Blah
break;
case "xxx.dev.yyy.com":
// Blah
break;
}
...but again, that only works if that's the complete string you're matching. It would fail if base_url_string
were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.
Update: Okay, so technically you can use a switch
for substring matching, but I wouldn't recommend it in most situations. Here's how (live example):
function test(str) {
switch (true) {
case /xyz/.test(str):
display("• Matched 'xyz' test");
break;
case /test/.test(str):
display("• Matched 'test' test");
break;
case /ing/.test(str):
display("• Matched 'ing' test");
break;
default:
display("• Didn't match any test");
break;
}
}
That works because of the way JavaScript switch
statements work, in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case
) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is true
, the first case
expression that results in true
will be the one that gets used.
RegExp can be used on the input string with the match
method too.
To ensure that we have a match in a case
clause, we will test the original str
value (that is provided to the switch
statement) against the input
property of a successful match
.
input
is a static property of regular expressions that contains the original input string.
When match
fails it returns null
. To avoid an exception error we use optional chaining operator (or the logical ||
conditional operator in legacy ES) before accessing the input
property.
const str = 'XYZ test';
switch (str) {
case str.match(/^xyz/)?.input:
console.log("Matched a string that starts with 'xyz'");
break;
case str.match(/test/)?.input:
console.log("Matched the 'test' substring");
break;
default:
console.log("Didn't match");
break;
}
Another approach is to use the String()
constructor to convert the resulting array that must have only 1 element (no capturing groups) and whole string must be captured with quantifiers (.*
) to a string. In case of a failure the null
object will become a 'null'
string. That may seem less convenient.
const str = 'XYZ test';
switch (str.toLowerCase()) {
case String(str.match(/^xyz.*/i)):
console.log("Matched a string without case sensitivity");
break;
case String(str.match(/.*tes.*/)):
console.log("Matched a string using a substring 'tes'");
break;
}
Anyway, a more elegant solution is to use the test
method instead of match
, i.e. /^find-this-in/.test(str)
with switch (true)
which simply returns a boolean value and it's easier to match without case sensitivity.
const str = 'haystack';
switch (true) {
case /^hay.*/.test(str):
console.log("Matched a string that starts with 'hay'");
break;
}
Just use the location.host property
switch (location.host) {
case "xxx.local":
settings = ...
break;
case "xxx.dev.yyy.com":
settings = ...
break;
}
Another option is to use input
field of a regexp match result:
str = 'XYZ test';
switch (str) {
case (str.match(/^xyz/) || {}).input:
console.log("Matched a string that starts with 'xyz'");
break;
case (str.match(/test/) || {}).input:
console.log("Matched the 'test' substring");
break;
default:
console.log("Didn't match");
break;
}
var token = 'spo';
switch(token){
case ( (token.match(/spo/) )? token : undefined ) :
console.log('MATCHED')
break;;
default:
console.log('NO MATCH')
break;;
}
--> If the match is made the ternary expression returns the original token
----> The original token is evaluated by case
--> If the match is not made the ternary returns undefined
----> Case evaluates the token against undefined which hopefully your token is not.
The ternary test can be anything for instance in your case
( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined
===========================================
(token.match(/spo/) )? token : undefined )
is a ternary expression.
The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).
If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).
Obviously token === token so the switch statement is matched and the case evaluated
It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.
It may be easier. Try to think like this:
:
// 'www.dev.yyy.com'
// 'xxx.foo.pl'
var url = "xxx.foo.pl";
switch (url.match(/\..*.\./)[0]){
case ".dev.yyy." :
console.log("xxx.dev.yyy.com");break;
case ".some.":
console.log("xxx.foo.pl");break;
} //end switch
Might be too late and all, but I liked this in case assignment :)
function extractParameters(args) {
function getCase(arg, key) {
return arg.match(new RegExp(`${key}=(.*)`)) || {};
}
args.forEach((arg) => {
console.log("arg: " + arg);
let match;
switch (arg) {
case (match = getCase(arg, "--user")).input:
case (match = getCase(arg, "-u")).input:
userName = match[1];
break;
case (match = getCase(arg, "--password")).input:
case (match = getCase(arg, "-p")).input:
password = match[1];
break;
case (match = getCase(arg, "--branch")).input:
case (match = getCase(arg, "-b")).input:
branch = match[1];
break;
}
});
};
you could event take it further, and pass a list of option and handle the regex with |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With