【问题标题】:Javascript Get absolute URL from relative escaped urlJavascript 从相对转义的 url 中获取绝对 URL
【发布时间】:2012-12-05 10:57:04
【问题描述】:

我有一个 js 函数,它接收一个像这样的 url:

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

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

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

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

Javascript 中是否有内置功能? (例如:在 C# 中,我会通过 URI 类来运行它。)

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

【问题讨论】:

标签: javascript parsing url


【解决方案1】:

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)

【讨论】:

  • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post
  • 事实上,它确实回答了这个问题。正如作者在 NickWoodham 的帖子中提到的那样,他没有可以使用的锚标签。正如我的回答所示,您不需要文档中的 HTML 标记来提供作者请求的功能。
【解决方案2】:

这应该可以解决问题:

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

【讨论】:

  • 谢谢..一个(愚蠢的)问题..我可以用while(arr.indexOf("..") > -1)替换while(!!~arr.indexOf(".."))吗?有什么区别?
  • 是的,你可以。不同之处在于!!~ 使用按位反转(~)仅在数组中搜索到的字符串时才输出“true-ish”值,并使用双布尔值not!!)来转换输出值为truefalse 而不是数字。不过,在性能方面,it barely makes a difference。我只是喜欢!!~ ;-)
【解决方案3】:

实际上要简单得多。

<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 中进行了测试。

【讨论】:

  • 我以前试过这个,但它不适用于我的特定场景......(我只收到 url,它可能未绑定到 DOM 元素)无论如何,谢谢。如果链接绑定到锚标记,这将是这样做的方法..
猜你喜欢
  • 2011-09-09
  • 2010-10-03
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 2014-12-12
  • 1970-01-01
相关资源
最近更新 更多