tags:

views:

49

answers:

2

So i want to join strings with relative urls in Javascript.

base url = "http://www.adress.com/more/evenmore"

with

relative url = "../../adress" => "http://www.adress.com/adress"
relative url = "../adress" => "http://www.adress.com/more/adress"

What would be the best way? I was thinking of using regexp and checking
how many "../" i find, then subtracting that amount from the baseurl and adding them to what is left.

A: 

location.href.split('/'); could be a start

chelmertz
+1  A: 

The following function decomposes the URL then resolves it.

function concatAndResolveUrl(url, concat) {
  var url1 = url.split('/');
  var url2 = concat.split('/');
  var url3 = [ ];
  for (var i = 0, l = url1.length; i < l; i ++) {
    if (url1[i] == '..') {
      url3.pop();
    } else if (url1[i] == '.') {
      continue;
    } else {
      url3.push(url1[i]);
    }
  }
  for (var i = 0, l = url2.length; i < l; i ++) {
    if (url2[i] == '..') {
      url3.pop();
    } else if (url2[i] == '.') {
      continue;
    } else {
      url3.push(url2[i]);
    }
  }
  return url3.join('/');
}
SHiNKiROU
nice. thanks mate!
heffaklump