Javascript port of PHP's ParseURL





2
Date Submitted Thu. Mar. 6th, 2008 3:09 AM
Revision 1 of 1
Helper Fordiman
Tags JavaScript | parse_url | PHP
Comments 0 comments
Simple. It's parse_url, from PHP, implemented in Javascript. Seen a lot of similar ones around the web, but they were all bulky code and none of them took advantage of the RegEx parser in JS.

Applied as a member of the String prototype, so just call as myURL.parseURL(); Will return a named object with naming identical to that of PHP's function.

Additional: if first argument is present, will break the querystring up into name/value pairs, unescaped, and return that instead of the raw querystriing.

String.prototype.parseURL = function(query) {
        var url=this,
                rx=/^((?:ht|f|nn)tps?)\:\/\/(?:([^\:\@]*)(?:\:([^\@]*))?\@)?([^\/]*)([^\?\#]*)(?:\?([^\#]*))?(?:\#(.*))?$/,
                rg=[null,'scheme','user','pass','host','path','query','fragment'],
                r=url.match(rx),i,q,ret={};
        if (r==null) return ret;
        for (i=1; i<rg.length; i++)
                if (r[i]!=undefined)
                        ret[rg[i]]=r[i];       
        if (ret.path=='') ret.path='/';
        if (query!=undefined && r[6]!=undefined) {
                var q=r[6];
                ret.query={};
                q=q.split('&');
                for (var i=0; i<q.length; i++) {
                        q[i]=q[i].split('=',2);
                        ret.query[unescape(q[i][0])]=unescape(q[i][1]);
                }
        }
        return ret;
}
 

Bryan Elliott

Comments

There are currently no comments for this snippet.

Voting

Votes Up


Newbie pixo
Scripter sehrgut

Votes Down