Skip to content

Instantly share code, notes, and snippets.

@westc
Last active February 7, 2019 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/8806225cdafc2479f0850b45cfdcf32c to your computer and use it in GitHub Desktop.
Save westc/8806225cdafc2479f0850b45cfdcf32c to your computer and use it in GitHub Desktop.
Gives the ability to get an absolute URL from a relative URL and an absolute base URL.
function getAbsUrl(relUrl, baseUrl) {
// Make sure baseUrl ends in a forward-slash
baseUrl = baseUrl.replace(/^(\w*\:\/\/[^\/\?]+)([\?#]|$)/, '$1/$2');
var firstChar = relUrl.charAt(0);
if (firstChar === '?') {
return baseUrl.replace(/[\?#].*$|$/, relUrl);
}
if (firstChar === '#') {
return baseUrl.replace(/#.*$|$/, relUrl);
}
if (firstChar === '/') {
return baseUrl.replace(/^(\w+:\/\/[^\/]+)\/.*/, '$1') + relUrl;
}
for (
relUrl = baseUrl.replace(/\/[^\/\?#]*([#\?].*)?$/, '/') + relUrl;
baseUrl = relUrl.replace(/(^[^\?#]+[^\/]\/)(?!\.\.\/)[^\/]+\/\.\.\//, '$1'), baseUrl !== relUrl;
relUrl = baseUrl
);
return relUrl.replace(/(^\w+:\/\/[^\/]+\/)(?:\.\.\/)+/, '$1');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment