Switch statement for string matching in JavaScript

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

提交回复
热议问题