Javascript从相对转义的网址获取绝对网址

时间:2012-12-05 10:57:04

标签: javascript parsing url

我有一个js函数,它接收一个url:

http://example.com/folder1/folder2/../page.html

请注意,网址是绝对的,但中间有../,因此它指向的实际html网页位于folder1而不是folder2

如何将http://example.com/folder1/folder2/../page.html转换为http://example.com/folder1/page.html

请注意,我的网址可能包含多个../

Javascript中是否有内置工具? (例如:在C#中我会通过URI类来运行它,它会为我执行此操作。)

更新:稍微澄清一下,我不想为此创建或使用DOM元素。

3 个答案:

答案 0 :(得分:2)



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)




答案 1 :(得分:1)

这应该可以解决问题:

function relativeToAbsolute(url){
    arr = url.split("/") // Cut the url up into a array
    while(!!~arr.indexOf("..")){ // If there still is a ".." in the array
        arr.splice(arr.indexOf("..") - 1, 2); // Remove the ".." and the element before it.
    }
    return arr.join("/"); // Rebuild the url and return it.
}
console.log(relativeToAbsolute("http://example.com/folder1/folder2/../page.html"));
console.log(relativeToAbsolute("http://example.com/folder1/folder2/../../page.html"));

// Returns:
// http://example.com/folder1/page.html
// http://example.com/page.html

答案 2 :(得分:1)

实际上要简单得多。

<a id="mylink" href="/static/img/photo.jpg">My Photo</a>

<script>
var javascript_object = document.getElementById('#mylink');
var url = javascript_object.href; //returns absolute url

//want to write it back? just reverse it
javascript_object.href = url;
</script>

免责声明:到目前为止,我只在Chrome中测试过。