使用 js 实现 urljoin 方法
需求:
在 js 中将两个网址信息拼接在一起。
如下代码如下:
String.prototype.endsWith = function (end) { return this.length > 0 && this.indexOf(end) + end.length == this.length; }; String.prototype.rfind = function (c) { for (let i = this.length - 1; i >= 0; i--) { if (this.split("")[i] == c) { return i; } } return -1; }; window.urljoin = function (url_base, relative_url) { let length = relative_url.length, relative_url2 = relative_url.replace(/\.\.\//g, ""), length2 = relative_url2.length, level_len = (length - length2) / 3; if (relative_url.indexOf("./") == 0) { return ( url_base.substring(0, url_base.rfind("/") + 1) + relative_url.substring(2) ); } else if (relative_url.indexOf("../") == 0) { let count = 0; for (let i = 0; i < url_base.length; i++) { let s = url_base[url_base.length - 1 - i]; if (s == "/") { count++; } if (count == level_len + 1) { return url_base.substring(0, url_base.length - i) + relative_url2; break; } } } else if (relative_url.indexOf("/") == 0) { return new URL(url_base).origin + relative_url; }else if(relative_url.indexOf('http://') == 0 || relative_url.indexOf('https://') == 0){ return relative_url } else { return ( url_base.substring(0, url_base.rfind("/") + 1) + relative_url ); } };