Skip to content

Instantly share code, notes, and snippets.

@spikegrobstein
Created December 10, 2010 01:43
Show Gist options
  • Save spikegrobstein/735629 to your computer and use it in GitHub Desktop.
Save spikegrobstein/735629 to your computer and use it in GitHub Desktop.
convert uri from href/src attribute to absolute-absolute URI given the relative servername and attribute value
function uri_to_absolute(server_name, uri) {
if (uri.match(/^#/)) {
return uri;
}
var m = server_name.match(/^((.+?\/\/[^\/]+)(.*))/);
var server_name = (m) ? m[2] : server_name;
var path = (m) ? m[3] : '';
// remove trailing slash on server_name if it exists
if (server_name.match(/\/$/)) {
m = server_name.match(/^(.+?)\/*$/);
server_name = m[1];
}
if (path.length > 0 && !path.match(/\/$/)) { // if the path does not end with a /
// trim the last path element
m = path.match(/^(.+?)\/[^\/]+$/);
path = m[1];
}
// remove leading slash on path
if (path.match(/^\//)) {
m = path.match(/^\/(.*)$/);
path = m[1];
}
if (path.length > 0) {
path = path + '/';
}
var final_output;
if (uri.match(/^\//)) { // if the URI starts with a /, then just prepend the server_name
final_output = server_name + uri;
} else if (uri.match(/^.+?:\/\//)) { // the URI has a protocol defined (http://), so return the uri
final_output = uri;
} else { // the URI is relative, so
final_output = server_name + '/' + path + uri;
}
// replace double-slashes
if (final_output.match(/:\/\/.*\/\//)) {
final_output.replace(/([^:])\/\//, "\1/");
}
return final_output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment