Skip to content

Instantly share code, notes, and snippets.

@spiralx
Last active December 22, 2015 09:38
Show Gist options
  • Save spiralx/6452828 to your computer and use it in GitHub Desktop.
Save spiralx/6452828 to your computer and use it in GitHub Desktop.
ES5 and 6 functions to parse URIs mostly following the RFC 1738 spec
/*jshint asi:true */
;(function(global) {
'use strict'
const parser = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
queryKeyParser = /(?:^|&)([^&=]*)=?([^&]*)/g,
keys = "href protocol authority userInfo user password host port relative path directory file query anchor".split(" ");
/**
* Creates a function parse_uri that takes a URL and parses it into
* its various components e.g. protocol, host, username, password,
* path, query etc. Takes a URL string to process, if none is passed
* it processes location.href by default.
*/
global.parseUri = uri => {
let href = uri || location.href,
m = parser.exec(href),
uriinfo = {
params: {}
}
keys.forEach((key, idx) => {
uriinfo[key] = m[idx] || ""
})
uriinfo.query.replace(queryKeyParser, (match, name, value) => {
/*jshint unused:false */
if (name) {
value = decodeURIComponent(value)
uriinfo.params[name] = parseFloat(value) || value
}
});
return uriinfo;
}
})(window)
/*jshint asi:true */
; (function(global) {
'use strict'
var parser = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
queryKeyParser = /(?:^|&)([^&=]*)=?([^&]*)/g,
keys = "href protocol authority userInfo user password host port relative path directory file query anchor".split(" ");
/**
* Creates a function parse_uri that takes a URL and parses it into
* its various components e.g. protocol, host, username, password,
* path, query etc. Takes a URL string to process, if none is passed
* it processes location.href by default.
*/
global.parseUri = function(uri) {
var href = uri || location.href,
m = parser.exec(href),
uriinfo = {
params: {}
}
keys.forEach(function(key, idx) {
uriinfo[key] = m[idx] || ""
});
uriinfo.query.replace(queryKeyParser, function(match, name, value) {
/*jshint unused: false */
if (name) {
value = decodeURIComponent(value)
uriinfo.params[name] = parseFloat(value) || value
}
})
return uriinfo
}
})(window)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment