Skip to content

Instantly share code, notes, and snippets.

@pjmelling
Forked from tkw1536/relativeUrl.js
Created January 26, 2017 20:03
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 pjmelling/bc2ea7511beb3c9052c81ac2e681f527 to your computer and use it in GitHub Desktop.
Save pjmelling/bc2ea7511beb3c9052c81ac2e681f527 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