Skip to content

Instantly share code, notes, and snippets.

@hackash
Last active October 7, 2016 21:18
Show Gist options
  • Save hackash/440c6cd74314d36eccdcbd16079dc7e6 to your computer and use it in GitHub Desktop.
Save hackash/440c6cd74314d36eccdcbd16079dc7e6 to your computer and use it in GitHub Desktop.
Extending string prototype with a function , that returns url relative to gives as an argument.
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('/');
};
console.log('case 1 ', '../d.html'.relativeTo('/a/b/c.html')); // output case 1 /a/d.html
console.log('case 2 ', 'g.html'.relativeTo('/a/b/c.html')); // output case 2 /a/b/g.html
console.log('case 3 ', './f/j.html'.relativeTo('/a/b/c.html')); // output case 3 /a/b/f/j.html
console.log('case 4 ', '../../k/w.html'.relativeTo('/a/b/c.html')); // output case 4 /k/w.html
console.log('case 5 ', 'https://www.google.com'.relativeTo('/a/b/c.html')); // output case 5 https://www.google.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment