fingerpich
fingerpich

Reputation: 9330

get url relative to another url in javascript

i want to get url relative to another url

for example

"../d.html".relativeTo("/a/b/c.html"); //==> "/a/d.html"

"g.html".relativeTo("/a/b/c.html"); //==> "/a/b/g.html"

"./f/j.html".relativeTo("/a/b/c.html"); //==> "/a/b/f/j.html"

"../../k/w.html".relativeTo("/a/b/c.html"); //==> "/k/w.html"

"http://www.google.com".relativeTo("/a/b/c.html"); //==> "http://www.google.com"

i think there is a simple solution for that because browsers does it for relative url links.

i have tried

String.prototype.relativeTo=function(input){
    if(/^https?:\/\//i.test(this)) {
        return this.valueOf();
    }
    else {
        var a = document.createElement("a");
        a.href = input.replace(/\w+\.\w+/, "") + this;
        return a.href;
    }
}

but it returns absolute url

is there some simple way to do that?

Upvotes: 0

Views: 86

Answers (1)

Ashot
Ashot

Reputation: 1300

Really interesting, anyway I would like to answer

String.prototype.startsWith = function (input) {
   return this.substring(0, input.length) === input;
};

String.prototype.relativeTo = function (input) {
   var toTop = /..\//gi;
   var abs = /^https?:\/\//i;
   var inCurrent = './';
   var matches;

   if (abs.test(this)) {
     return this.valueOf();
   }

   function getLastSegmentIndex() {
     return (input.lastIndexOf('/') + 1) - (input.length - 1);
   }

   try {
     matches = this.match(toTop).length;
   } catch (e) {
     matches = 0;
   }

   if (!matches) {
     return input.slice(0, -getLastSegmentIndex()) + this.valueOf();
   } else if (this.startsWith(inCurrent)) {
     return input.slice(0, -getLastSegmentIndex()) +     


     this.replace(inCurrent, '');
   }

   var segments = input.split('/');
   var i = 0;

   for (; i < matches + 1; i++) {
    segments.pop();
   }

   segments.push((this.replace(toTop, '')));
   return segments.join('/');
};

Upvotes: 2

Related Questions