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.
Otherwise, while you can use a switch for substring matching, but I wouldn't recommend it in most situations (more below). Here's how it would look:
function test(str) {
switch (true) {
case /xyz/.test(str):
console.log("• Matched 'xyz' test");
break;
case /test/.test(str):
console.log("• Matched 'test' test");
break;
case /ing/.test(str):
console.log("• Matched 'ing' test");
break;
default:
console.log("• Didn't match any test");
break;
}
}
function test(str) {
console.log("Testing '" + str + "':");
switch (true) {
case /xyz/.test(str):
console.log("• Matched 'xyz' test");
break;
case /test/.test(str):
console.log("• Matched 'test' test");
break;
case /ing/.test(str):
console.log("• Matched 'ing' test");
break;
default:
console.log("• Didn't match any test");
break;
}
}
test("testing");
test("xyz123");
test("foo");
test("fooing");
.as-console-wrapper {
max-height: 100% !important;
}
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.
The reason I wouldn't recommend it in most situations is that it's cumbersome as well as being somewhat surprising (to people reading it later) compared to the equivalent if/else if/else:
function test(str) {
if (/xyz/.test(str)) {
console.log("• Matched 'xyz' test");
} else if (/test/.test(str)) {
console.log("• Matched 'test' test");
} else if (/ing/.test(str)) {
console.log("• Matched 'ing' test");
} else {
console.log("• Didn't match any test");
}
}
Live Example:
function test(str) {
console.log("Testing '" + str + "':");
if (/xyz/.test(str)) {
console.log("• Matched 'xyz' test");
} else if (/test/.test(str)) {
console.log("• Matched 'test' test");
} else if (/ing/.test(str)) {
console.log("• Matched 'ing' test");
} else {
console.log("• Didn't match any test");
}
}
test("testing");
test("xyz123");
test("foo");
test("fooing");
.as-console-wrapper {
max-height: 100% !important;
}
In both cases, the code does the same things in the same order, but unless you're well-versed in JavaScript arcana, the latter is clearer (arguably even if you are).