fingerpich fingerpich - 2 months ago 13
Javascript Question

get url relative to another url in javascript

i want to implement

url.relativeTo(url);


which can work with every 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"


is there any simple method to do that?

Answer

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;
   } 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('/');
};