jQuery - 从包含“../”的URL字符串获取绝对路径

时间:2014-07-03 12:49:31

标签: javascript jquery url

我不知道之前是否已经回答过。我不知道该搜索什么。

我想知道的是,是否存在针对以下问题的jquery函数。

假设我有一个这样的网址字符串 - www.example.com/a/b/../c 我想得到www.example.com/a/c

1 个答案:

答案 0 :(得分:4)

一种简单的方法是创建一个link元素,设置其href属性,然后阅读它。

var a = document.createElement("a");
a.href = "http://www.example.com/a/b/../c";
var resolved = a.href;
console.log(resolved); // "http://www.example.com/a/c"

或使用一些jQuery:

var resolved = $("<a>").prop("href", "http://www.example.com/a/b/../c").prop("href");
console.log(resolved); // "http://www.example.com/a/c"

Live Example

这相对于当前文档的路径有效,但上面的URL并不重要,因为URL是绝对的。

请注意,我们在这里使用反射属性而不是属性非常重要。