Regex for a URL Connection String

前端 未结 1 2016
耶瑟儿~
耶瑟儿~ 2021-01-24 01:13

Is there a known JavaScript regular expression to match an entire URL Connection String?

protocol://user:password@hostname:12345/segment1/segment2?p1=val1&p2         


        
相关标签:
1条回答
  • 2021-01-24 01:51

    Something like this ?

    function url2obj(url) {
        var pattern = /^(?:([^:\/?#\s]+):\/{2})?(?:([^@\/?#\s]+)@)?([^\/?#\s]+)?(?:\/([^?#\s]*))?(?:[?]([^#\s]+))?\S*$/;
        var matches =  url.match(pattern);
        var params = {};
        if (matches[5] != undefined) { 
           matches[5].split('&').map(function(x){
             var a = x.split('=');
             params[a[0]]=a[1];
           });
        }
    
        return {
            protocol: matches[1],
            user: matches[2] != undefined ? matches[2].split(':')[0] : undefined,
            password: matches[2] != undefined ? matches[2].split(':')[1] : undefined,
            host: matches[3],
            hostname: matches[3] != undefined ? matches[3].split(/:(?=\d+$)/)[0] : undefined,
            port: matches[3] != undefined ? matches[3].split(/:(?=\d+$)/)[1] : undefined,
            segments : matches[4] != undefined ? matches[4].split('/') : undefined,
            params: params 
        };
    }
    
    console.log(url2obj("protocol://user:password@hostname:12345/segment1/segment2?p1=val1&p2=val2"));
    console.log(url2obj("http://hostname"));
    console.log(url2obj(":password@"));
    console.log(url2obj("?p1=val1"));
    console.log(url2obj("ftp://usr:pwd@[FFF::12]:345/testIP6"));

    A test for the regex pattern here on regex101

    0 讨论(0)
提交回复
热议问题