Skip to content

Instantly share code, notes, and snippets.

@tkw1536
Last active January 26, 2017 20:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tkw1536/6980004 to your computer and use it in GitHub Desktop.
Save tkw1536/6980004 to your computer and use it in GitHub Desktop.
Resolve a relative URL in client-side JavaScript with jQuery.
/*
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