Skip to content

Instantly share code, notes, and snippets.

@MChorfa
Forked from Yaffle/URLUtils.js
Created August 3, 2011 01:36
Show Gist options
  • Save MChorfa/1121697 to your computer and use it in GitHub Desktop.
Save MChorfa/1121697 to your computer and use it in GitHub Desktop.
/*jslint regexp: true, sloppy: true, maxerr: 50, indent: 2 */
function parseURI(url) {
var m = String(url).match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
}
function absolutizeURI(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('');
}
href = parseURI(String(href || '').replace(/^\s+|\s+$/g, ''));
base = parseURI(String(base || '').replace(/^\s+|\s+$/g, ''));
if (href === null || base === null) {
return null;
}
var res = {};
if (href.protocol || href.authority) {
res.authority = href.authority;
res.pathname = removeDotSegments(href.pathname);
res.search = href.search;
} else {
if (!href.pathname) {
res.pathname = base.pathname;
res.search = href.search || base.search;
} else {
if (href.pathname.charAt(0) === '/') {
res.pathname = removeDotSegments(href.pathname);
} else {
if (base.authority && !base.pathname) {
res.pathname = removeDotSegments('/' + href.pathname);
} else {
res.pathname = removeDotSegments(base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname);
}
}
res.search = href.search;
}
res.authority = base.authority;
}
res.protocol = href.protocol || base.protocol;
res.hash = href.hash;
return res.protocol + res.authority + res.pathname + res.search + res.hash;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment