[英]get url relative to another url in javascript
i want to get url relative to another url我想获取相对于另一个 url 的 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.我认为有一个简单的解决方案,因为浏览器是针对相对 url 链接进行的。
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?有没有一些简单的方法可以做到这一点?
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('/');
};
Please go through the URL below. 请通过下面的URL。 Hope this will help you.
希望这会帮助你。
https://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html https://docs.oracle.com/javase/tutorial/networking/urls/creatingUrls.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.