Last active
February 7, 2019 20:05
-
-
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.
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 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