1

我有一个 js 函数,它接收如下 URL:

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

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

我怎样才能转换http://example.com/folder1/folder2/../page.htmlhttp://example.com/folder1/page.html

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

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

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

4

3 回答 3

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)

于 2014-05-06T03:08:19.760 回答
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
于 2012-12-05T11:42:07.230 回答
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 中进行了测试。

于 2012-12-27T23:06:00.873 回答