Switch statement for string matching in JavaScript

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/"
    };
}

9 Answers
9

Leave a Comment