Skip to content

Instantly share code, notes, and snippets.

@cers
Created April 28, 2009 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cers/102849 to your computer and use it in GitHub Desktop.
Save cers/102849 to your computer and use it in GitHub Desktop.
function absolutifyUrls(data, sourceUrl) {
var relRe = /:\/\//;
var domainRe = /.*?\/\/[^?/]*/;
var pathRe = /.*\//;
if (sourceUrl.length-sourceUrl.replace(/\//g,"").length==2) {
sourceUrl += "/";
}
if (typeof(data)=="string") {
data = jQuery("<div>"+data+"</div>");
} else if (typeof(data)=="object") {
data = jQuery('<div>').append(data);
}
jQuery("a",data).each(function correctUrls(){
var el = jQuery(this);
var href = el.attr("href");
if (!relRe.exec(href)) {
if (href[0] == "/") {
href = domainRe.exec(sourceUrl)+href;
}
else {
href = pathRe.exec(sourceUrl)+href;
}
el.attr("href", href);
}
});
return data.html();
};
CmdUtils.CreateCommand({
name: "example",
preview: function(pblock) {
pblock.innerHTML = "<h3>Tests</h3><br>";
pblock.innerHTML += absolutifyUrls("<a href='/search?q=ubiquity'>ubiquity</a><br>", "http://google.com/");
pblock.innerHTML += absolutifyUrls("<a href='../search?q=ubiquity'>ubiquity</a><br>", "http://google.com/");
pblock.innerHTML += absolutifyUrls("<a href='../search?q=ubiquity'>ubiquity</a><br>", "http://google.com/help");
pblock.innerHTML += absolutifyUrls("<a href='search?q=ubiquity'>ubiquity</a><br>", "http://google.com/help");
pblock.innerHTML += absolutifyUrls("<a href='search?q=ubiquity'>ubiquity</a><br>", "http://google.com");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment