How do I write a switch for the following conditional?
If the url contains "foo", then settings.base_url is "bar".
The following is achieving the effect required but I’ve a feeling this would be more manageable in a switch:
var doc_location = document.location.href;
var url_strip = new RegExp("http:\/\/.*\/");
var base_url = url_strip.exec(doc_location)
var base_url_string = base_url[0];
//BASE URL CASES
// LOCAL
if (base_url_string.indexOf('xxx.local') > -1) {
settings = {
"base_url" : "http://xxx.local/"
};
}
// DEV
if (base_url_string.indexOf('xxx.dev.yyy.com') > -1) {
settings = {
"base_url" : "http://xxx.dev.yyy.com/xxx/"
};
}
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:
…but again, that only works if that’s the complete string you’re matching. It would fail if
base_url_stringwere, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.Otherwise, while you can use a
switchfor substring matching, but I wouldn’t recommend it in most situations (more below). Here’s how it would look:That works because of the way JavaScript
switchstatements 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 keywordcase) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression istrue, the firstcaseexpression that results intruewill 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:Live Example:
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).