我有一个 js 函数,它接收如下 url:
http://example.com/folder1/folder2/../page.html
注意 url 是绝对的,但它在中间有 ../
所以它指向的实际 html 页面位于 folder1
而不是 文件夹2
。
如何将 http://example.com/folder1/folder2/../page.html
转换为 http://example.com/folder1/page.html
?
请注意,我的网址可能包含多个 ../
在 Javascript 中有内置工具吗? (例如:在 C# 中,我将通过为我执行此操作的 URI 类运行它。)
更新:澄清一点,我不想为此创建或使用 DOM 元素。
最佳答案
function relativeToAbsolute(relativeUrl) {
var a = document.createElement('a');
a.href = relativeUrl;
return a.href;
}
url = relativeToAbsolute("http://example.com/folder1/folder2/../page.html");
console.log(url)
关于Javascript 从相对转义的 URL 获取绝对 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13721651/