前端实现相对路径转绝对路径的几种方法
# 1.使用a标签
function getAbsoluteUrlByA (url) {
var a = document.createElement("a")
a.href = url
a.href = a.href //ie8的问题
return a.href
}
1
2
3
4
5
6
7
2
3
4
5
6
7
注:node.js 不适用
# 2.数组处理
function getAbsoluteUrl(url) {
url = url.replace(/&|&/g, "&");
if (url.startsWith("http") || url.startsWith("javascript:") || url === "about:blank") return url;
if (url.startsWith("//")) {
return window.location.protocol + url
}
var stack = window.location.href.split("/");
stack.pop()
var parts = url.split("/")
for (var i = 0; i < parts.length; i++) {
if (parts[i] == ".")
continue;
if (parts[i] == "..")
stack.pop();
else
stack.push(parts[i]);
}
return stack.join("/");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 3.正则字符替换
function relPathToAbs (sRelPath) {
var nUpLn, sDir = "", sPath = location.pathname.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, "$1"));
for (var nEnd, nStart = 0; nEnd = sPath.indexOf("/../", nStart), nEnd > -1; nStart = nEnd + nUpLn) {
nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp("(?:\\\/+[^\\\/]*){0," + ((nUpLn - 1) / 3) + "}$"), "/");
}
return sDir + sPath.substr(nStart);
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
转自MDN
# 结论
测试多次,总体速度相近,第二种可能会快一点点
编辑 (opens new window)
上次更新: 2024/09/01, 23:56:56