如何在JavaScript中从location.href获取请求URI?

24

location.href 返回的是这样的:

http://stackoverflow.com/questions/ask

但我只想获取questions/ask(第一个字符没有/

如何实现?

5个回答

36

location.pathname.substr(1)是什么意思。


@wamp substr有一个可选的长度参数,而substring则有一个可选的结束索引参数。在这种情况下,如果只想要从起始位置开始的所有内容,它们将执行相同的操作。 - iamface
我可以如何使用 href 字符串变量代替 location.pathname - Dimitri Kopriwa

16

位置(location)对象具有pathname属性。

这将给出/questions/ask,要删除第一个字符,请使用substring(1)

var path = location.pathname.substring(1);

哪个更好,substr还是substring - wamp
2
@wamp:没有“更好”的(你到底是什么意思?)。它们的工作方式不同。substr函数将长度作为第二个参数,而substring函数则使用另一个索引(提取字符串的上限)。在这种情况下,无论您使用哪个函数都没有关系(我假设内部实际上是相同的函数)。 - Felix Kling

3
您可以使用location.pathname.substring(1)

1
var uri = window.location.href.substr(window.location.protocol.length + window.location.hostname.length + 2);

这段代码还包括GET和HASHTAGS(基本上是主机名后面的所有内容)。

1
如果您需要查询参数,可以使用以下代码:

var path = (window.location.pathname+window.location.search).substr(1);

如果您需要访问哈希,也可以使用以下代码:
var path = (window.location.href.replace(window.location.origin, '')).substr(1);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接