Switch statement for string matching in JavaScript

前端 未结 9 1487
深忆病人
深忆病人 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.

    0 讨论(0)
  • 2020-11-29 16:19
    var token = 'spo';
    
    switch(token){
        case ( (token.match(/spo/) )? token : undefined ) :
           console.log('MATCHED')    
        break;;
        default:
           console.log('NO MATCH')
        break;;
    }
    


    --> If the match is made the ternary expression returns the original token
    ----> The original token is evaluated by case

    --> If the match is not made the ternary returns undefined
    ----> Case evaluates the token against undefined which hopefully your token is not.

    The ternary test can be anything for instance in your case

    ( !!~ base_url_string.indexOf('xxx.dev.yyy.com') )? xxx.dev.yyy.com : undefined 
    

    ===========================================

    (token.match(/spo/) )? token : undefined ) 
    

    is a ternary expression.

    The test in this case is token.match(/spo/) which states the match the string held in token against the regex expression /spo/ ( which is the literal string spo in this case ).

    If the expression and the string match it results in true and returns token ( which is the string the switch statement is operating on ).

    Obviously token === token so the switch statement is matched and the case evaluated

    It is easier to understand if you look at it in layers and understand that the turnery test is evaluated "BEFORE" the switch statement so that the switch statement only sees the results of the test.

    0 讨论(0)
  • 2020-11-29 16:22

    You could also make use of the default case like this:

        switch (name) {
            case 't':
                return filter.getType();
            case 'c':
                return (filter.getCategory());
            default:
                if (name.startsWith('f-')) {
                    return filter.getFeatures({type: name})
                }
        }
    
    0 讨论(0)
  • 2020-11-29 16:26

    Might be too late and all, but I liked this in case assignment :)

    function extractParameters(args) {
        function getCase(arg, key) {
            return arg.match(new RegExp(`${key}=(.*)`)) || {};
        }
    
        args.forEach((arg) => {
            console.log("arg: " + arg);
            let match;
            switch (arg) {
                case (match = getCase(arg, "--user")).input:
                case (match = getCase(arg, "-u")).input:
                    userName = match[1];
                    break;
    
                case (match = getCase(arg, "--password")).input:
                case (match = getCase(arg, "-p")).input:
                    password = match[1];
                    break;
    
                case (match = getCase(arg, "--branch")).input:
                case (match = getCase(arg, "-b")).input:
                    branch = match[1];
                    break;
            }
        });
    };
    

    you could event take it further, and pass a list of option and handle the regex with |

    0 讨论(0)
  • 2020-11-29 16:34

    Just use the location.host property

    switch (location.host) {
        case "xxx.local":
            settings = ...
            break;
        case "xxx.dev.yyy.com":
            settings = ...
            break;
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题