Switch statement for string matching in JavaScript

前端 未结 9 1503
深忆病人
深忆病人 2020-11-29 15:46

How do I write a swtich for the following conditional?

If the url contains \"foo\", then settings.base_url is \"bar\".

The following is achi

9条回答
  •  悲哀的现实
    2020-11-29 16:34

    Another option is to use input field of a regexp match result:

    str = 'XYZ test';
    switch (str) {
      case (str.match(/^xyz/) || {}).input:
        console.log("Matched a string that starts with 'xyz'");
        break;
      case (str.match(/test/) || {}).input:
        console.log("Matched the 'test' substring");        
        break;
      default:
        console.log("Didn't match");
        break;
    }
    

提交回复
热议问题