Reputation: 6564
var path = location.pathname;
switch(path){
case (/\/memberlist/).test(path) :getCSS('url-22.css'); break;
case (/\/register/).test(path): getCSS('url-6.css'); break;
case (/buy-credits/g).test(path): getCSS('url-7.css'); break;
case (/\/?u(\d+)friends$/).test(path): getCSS('url-8.css'); break;
case (/\/privmsg/).test(path): getCSS('url-9.css'); break;
case (/\/?u(\d+)wall$/).test(path): getCSS('url-4.css'); break;
}
function getCSS(url,media){
var a = document.createElement('link');
a.href=url;
a.media= media || 'screen';
a.rel="stylesheet";
return (document.getElementsByTagName('head')[0].appendChild(a));
}
That is my code, and for some reason it's not running the function that should run. For testing purpose we could change var path="/memberlist"
and it still won't run. Can someone explain to me why this won't run. Don't really use switch statements
Upvotes: 9
Views: 11870
Reputation: 236
Have a look
switch(str){
case (/(abc|xyz)/.test(str) ? str : false):
// Do some stuff
break;
default:
// Do default stuff
}
Upvotes: 0
Reputation: 5272
None of the answers posted show a correct method to use a RegExp pattern in a switch case so I thought I'd post:
switch (myVar) {
case 'case1':
/...do work
break
case /[a-z]*/.test(myVar) && myVar:
/...regex match, do work
break
}
Upvotes: 9
Reputation: 122936
Just for the record, the switch case
could be rewritten to:
getCSS(
/\/memberlist/).test(path) && 'url-22.css' ||
/\/register/).test(path) && 'url-6.css' ||
/buy-credits/g).test(path) && 'url-7.css' ||
/\/?u(\d+)friends$/) && 'url-8.css' ||
/\/privmsg/).test(path) && 'url-9.css' ||
/\/?u(\d+)wall$/).test(path) && 'url-4.css' ||
'default'
);
Or rewrite getCSS, using a helper object
var path2url = {
css: [
{re: /\/register/, css: 'url-22.css'},
{re: /buy-credits/g, css: 'url-6.css'},
{re: /\/?u(\d+)friends$/, css: 'url-8.css'},
{re: /\/privmsg/, css: 'url-8.css'},
{re: /\/?u(\d+)wall$/, css: 'url-4.css'}
],
getURL: function(path) {
var i = this.css.length;
while (--i) {
if (this.css[i].re.test(path)) {
return this.css[i].css;
}
}
return null; // or something default
}
};
function getCSS(path,media){
var a = document.createElement('link');
a.href= path2url.getURL(path); // <=
a.media= media || 'screen';
a.rel="stylesheet";
return (document.getElementsByTagName('head')[0].appendChild(a));
}
Upvotes: 2
Reputation: 4279
change
switch(path){
to
switch(true){
as you can see in thread I'm reffering to in comment.
Upvotes: 10
Reputation: 785481
switch-case
doesn't work that way.
regex.test()
method returns a boolean (true/false) and you are comparing that against the input string itself which will not be true for any of the case
statement.
You need to convert switch-case
into multiple if / else if / else
block to execute your logic.
Upvotes: 2