Javascript Parse URL Function


 1:var parse_url = function (uri){
 2:    if (typeof uri == 'undefined') {
 3:        uri = location.href;
 4:    }
 5:    else if (uri[0] == '/'){
 6:        uri = location.host + uri;
 7:    }
 8:    var url = uri.match(/^([^:]*:\/\/)?([^:]*:[^@]*@)?([^\/:]*\.[^\/:]*)?(:[^\/]*)?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i);
 9:    delete url.input;
10:    url.protocol = ((url[1])?url[1]:'http://').split('://')[0];
11:    url.user = (url[2])?url[2].split(':')[0]:undefined;
12:    url.password = (url[2])?url[2].split(':')[1].split('@')[0]:undefined;
13:    url.host = (url[3])?url[3]:location.host;
14:    url.hostname = url.host;
15:    url.port = (url[4])?((isNaN(parseInt(url[4].split(':')[1])))?80:parseInt(url[4].split(':')[1])):80;
16:    url.path = (url[5])?url[5]:'/';
17:    url.pathname = url.path;
18:    url.search = (url[6])?url[6].split('?')[1]:undefined;
19:    url.query = url.search;
20:    url.fragment = (url[7])?url[7].split('#')[1]:undefined;
21:    url.hash = url.fragment;
22:    url.href = ''
23:        + url.protocol + '://'
24:        + ((url.user)?url.user+':'+url.password+'@':'')
25:        + url.host
26:        + ((url.port != 80)?':'+url.port:'')
27:        + url.path
28:        + ((url.search)?'?'+url.search:'')
29:        + ((url.fragment)?'#'+url.fragment:'');
30:    return url;
31:}// /parse_url()
  1. #1 by jon on February 12, 2009 - 3:32 am

    slightly better regex:

    var regex = /^([^:]*:\/\/)?([^:]*:[^@]*@)?([^\/:\?]*\.[^\/:\?]*)?(:[^\/]*)?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i;

    Fixes: http://foo.com?blah

(will not be published)