Last active
February 19, 2016 16:29
-
-
Save robyviggy/c9573471e0d752ff7e12 to your computer and use it in GitHub Desktop.
Javascript URL parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function | |
function parseUrl(e) { | |
var n = { | |
strictMode: false, | |
key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], | |
q: { | |
name: "queryKey", | |
parser: /(?:^|&)([^&=]*)=?([^&]*)/g | |
}, | |
parser: { | |
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, | |
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ | |
} | |
}; | |
var r = n.parser[n.strictMode ? "strict" : "loose"].exec(e), | |
i = {}, s = 14; | |
while (s--) i[n.key[s]] = r[s] || ""; | |
i[n.q.name] = {}; | |
i[n.key[12]].replace(n.q.parser, function (e, t, r) { | |
if (t) i[n.q.name][t] = r | |
}); | |
return i; | |
} | |
// usage example | |
var url = document.location.href; | |
var parser = parseUrl(url); | |
alert ('Source: ' +parser.source+'\n ' | |
+'host: '+ parser.host + '\n' | |
+'relative: '+ parser.relative+'\n' | |
+'path: '+ parser.path + '\n' | |
+'authority: '+ parser.authority + '\n' | |
+'directory: '+ parser.directory + '\n' | |
+'query: '+ parser.query + '\n'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment