Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making relative url absolute using arbitrary root in javascript

Tags:

javascript

url

Assuming that I'm on a page on a different domain (mydomain.com) and that the relative url only exists in code (not in the DOM)

How do I combine two arbitrary urls entirely in javascript?

var a = 'http://example.com/some/path/';
var b = '../other/path/';
var c = magicUrlCombine(a,b);
assert(c == 'http://example.com/some/other/path/');

It should also work for

var a = 'http://example.com/some/path/';
var b = 'http://pink-unicorns.com/some/other/path/';
var c = magicUrlCombine(a,b);
assert(c == 'http://pink-unicorns.com/some/other/path/');

EDIT:

I'm looking for a completely general function for combining an absolute url with an arbitrary url. The same logic as the browser uses for resolving links but for urls that are not in the HTML of the page and/or not relative to the current location.href.

var a = 'http://example.com/a/b/c/';
var b = '../d/e/';
assert(c == 'http://example.com/a/b/d/e/')

OR

var b = '/f/g/';
assert(c == 'http://example.com/f/g/')

OR

var b = 'http://jquery.com/h/i/';
assert(c == 'http://jquery.com/h/i/')

EDIT 2:

node.js has a url module that has the right functionality, but I haven't found a nice way of reusing it on the client side. (how to use node.js module system on the clientside)

I managed to hack my way through making it work but it's not really a solution I feel comfortable putting into a production site. Hackety hack

like image 324
Jesper Larsen-Ledet Avatar asked May 10 '11 08:05

Jesper Larsen-Ledet


1 Answers

JQuery Mobile has it

$.mobile.path.makeUrlAbsolute(relPath, absPath)

console.log($.mobile.path.makeUrlAbsolute('../d/e/', 'http://example.com/a/b/c/'));
console.log($.mobile.path.makeUrlAbsolute('/f/g/', 'http://example.com/a/b/c/'));
console.log($.mobile.path.makeUrlAbsolute('http://jquery.com/h/i/', 'http://example.com/a/b/c/'));

all give the expected results

like image 141
Jesper Larsen-Ledet Avatar answered Oct 05 '22 12:10

Jesper Larsen-Ledet