-
-
Save pjmelling/bc2ea7511beb3c9052c81ac2e681f527 to your computer and use it in GitHub Desktop.
Resolve a relative URL in client-side JavaScript with jQuery.
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
/* | |
Resolves a relative url | |
@param url Url to resolve | |
@param base Optional. Base url to use. | |
@param isDir Optional. If set to true, will return a directory name ending with a slash. | |
*/ | |
var resolve = function(url, base, isDir){ | |
var resolveWithBase = false; | |
var baseUrl, oldBase, newBase; | |
if(typeof base == "string"){ | |
resolveWithBase = true; | |
baseUrl = arguments.callee(base, true); | |
oldBase = jQuery("base").detach(); | |
newBase = jQuery("<base>").attr("href", baseUrl).appendTo("head"); | |
} | |
var el= document.createElement('div'); | |
el.innerHTML= '<a href="'+jQuery('<span/>').text(url).html()+'">x</a>'; | |
var url = el.firstChild.href; | |
if(resolveWithBase){ | |
newBase.remove(); | |
oldBase.appendTo("head"); | |
} | |
if( (base === true || isDir === true ) && url[url.length - 1] != "/"){url = url + "/"; } | |
return url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment