开发者

Switch with partial values/regular expressions?

开发者 https://www.devze.com 2023-02-23 07:45 出处:网络
So lets say I had this switch: switch(str){ case \"something\": //a defined value // ... break; case /#[a-zA-Z]{1,}/ //Matches \"#\" followed by a letter

So lets say I had this switch:

switch(str){
  case "something": //a defined value
    // ...
  break;
  case /#[a-zA-Z]{1,}/ //Matches "#" followed by a letter
}

I'm almost sure that the above is almost impossib开发者_运维技巧le...but what would be the best way to achieve something similar? Maybe just plain if..else..ifs? That'd be boring...

So how would you achieve this?


You can get the matches for various patterns before you begin the switch, and set the cases to the index of the match.

(Other conditionals would be easier to read, if not more efficient.)

//var str= 'something';
var str='#somethingelse';
var M=  /^(something)|(#[a-zA-Z]+)$/.exec(str);
if(M){
    switch(M[0]){
        case M[1]:
        // ...
        alert(M[1]);
        break;
        case M[2]:
        //...
        alert(M[2])
        break;
    }
}


You can use a single regexp. It is not necessarily less boring but it gets the job done.

var result = /(something)|(#[a-zA-Z]{1,})/.exec(str);
if (!result) {
    // Handle error?
} else if (result[1]) {
    // something
} else if (result[2]) {
    // #[a-zA-Z]{1,} 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消