我想获取相对于另一个网址的网址
例如
"../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"
我认为有一个简单的解决方案,因为浏览器是为相对网址链接做的。
我试过了
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;
}
}
但它返回绝对网址
有一些简单的方法吗?
答案 0 :(得分:2)
真有意思,无论如何我想回答
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('/');
};
答案 1 :(得分:0)
请浏览以下网址。希望这会对你有所帮助。
https://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html