Switch statement for string matching in JavaScript

前端 未结 9 1499
深忆病人
深忆病人 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:13

    RegExp can be used on the input string not just technically but practically with the match method too.

    Because the output of the match() is an array we need to retrieve the first array element of the result. When the match fails, the function returns null. To avoid an exception error we will add the || conditional operator before accessing the first array element and test against the input property that is a static property of regular expressions that contains the input string.

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

    Another approach is to use the String() constructor to convert the resulting array that must have only 1 element (no capturing groups) and whole string must be captured with quanitifiers (.*) to a string. In case of a failure the null object will become a "null" string. Not convenient.

    str = 'haystack';
    switch (str) {
      case String(str.match(/^hay.*/)):
        console.log("Matched a string that starts with 'hay'");
        break;
    }
    

    Anyway, a more elegant solution is to use the /^find-this-in/.test(str) with switch (true) method which simply returns a boolean value and it's easier to search without case sensitivity.

提交回复
热议问题