Regex for a URL Connection String

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

protocol://user:[email protected]:12345/segment1/segment2?p1=val1&p2=val2

I'm looking for a single regular expression that would help me translate such a connection string into an object:

    protocol: 'protocol',
    user: 'user',
    password: 'password',
    host: 'hostname:12345',
    hostname: 'hostname',
    port: 12345,
    segments: ['segment1', 'segment2'],
    params: {
        p1: 'val1',
        p2: 'val2'

Also, I want every single part of the connection string to be optional, so the missing parameters can be filled by values from the environment.


Standard RFC 3986 rules should apply to all the parts when it comes to the valid symbols.

I'm looking for something that would work in both Node.js and all browsers.

I've done a separate parsing piece-by-piece within connection-string, but the problem with that - it doesn't allow to validate, i.e. to tell if the whole thing is valid.



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) { 
         var a = x.split('=');

    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:[email protected]:12345/segment1/segment2?p1=val1&p2=val2"));
console.log(url2obj(":[email protected]"));
console.log(url2obj("ftp://usr:[email protected][FFF::12]:345/testIP6"));

A test for the regex pattern here on regex101


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.