9
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

EasyBB
  • 6,176
  • 9
  • 47
  • 77
  • switch you always compare with path. So make your string you enter tehre the same as path. for use of substring like you try see here :http://stackoverflow.com/questions/2896626/switch-statement-for-string-matching-in-javascript – chillworld Feb 11 '14 at 06:37

5 Answers5

10

change

switch(path){

to

switch(true){

as you can see in thread I'm reffering to in comment.

chillworld
  • 4,207
  • 3
  • 23
  • 50
  • Yes I saw this earlier, though after anubhava explained it I understood why it wasn't returning anything and that's because what it was looking for wasn't true or false. it works now thanks. – EasyBB Feb 11 '14 at 06:47
  • Related answer that has an example: https://stackoverflow.com/a/47281232/2193968 – Jerry Jeremiah Nov 19 '19 at 21:14
8

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
}
Cory Robinson
  • 4,616
  • 4
  • 36
  • 53
2

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Oh so the switch would have to be set for true? – EasyBB Feb 11 '14 at 06:38
  • For your updated answer, I just changed the switch to true and it's working now perfectly fine. I changed it from an `if / else if / else` so it was minimized and not so cluttered. – EasyBB Feb 11 '14 at 06:39
  • switch is useful only when multiple values need to be matched, here you will get either true or false from `regex.test()` method. – anubhava Feb 11 '14 at 06:40
  • That is true, which if none exist it'll break. – EasyBB Feb 11 '14 at 06:42
  • @anubhava actually it can see the link I set in comment. He's trying to do substring switching. but he need to switch for true and not path – chillworld Feb 11 '14 at 06:43
  • There will be multiple times I would have to write an `else if` and I don't want to do that, and in size and readability switch statement is the best option, no? Maybe I'm not getting your point. – EasyBB Feb 11 '14 at 06:44
  • You can avoid all switch and if completely. If I have to do it I would store all my regex in an array and call `test()` while iterating the array and breaking out as soon we get a match. Link provided by @chillworld also have a work-around to use `switch(true)` for this type of use-case. – anubhava Feb 11 '14 at 06:47
  • Yes looping is plausible for the situation, though I'm working on this code for a friend and don't feel like telling him how to update it, well explaining it to him. Thanks guys. – EasyBB Feb 11 '14 at 06:49
2

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));    
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

Have a look

switch(str){
    case (/(abc|xyz)/.test(str) ? str : false):
        // Do some stuff
        break;
    default:
        // Do default stuff         
}
DebuggerCoder
  • 236
  • 4
  • 15
  • Why -1 for this answer ? – DebuggerCoder Jun 29 '17 at 06:11
  • Did you even tried your own code? Your case returns true or false but you're matching the boolean with a string. You have to change `switch(str)` to `switch(true)` to get this to work. Also the additional bool-check isn't neccessary, since `test()` already returns true or false. – Pandora Dec 02 '18 at 19:37