如何从javascript中的location.href获取请求uri?

wam*_*amp 16 javascript dom

我得到的location.href是这样的:

http://stackoverflow.com/questions/ask
Run Code Online (Sandbox Code Playgroud)

但我只想得到questions/ask(/第一个角色没有)

怎么做到这一点?

Mar*_*rth 27

location.pathname.substr(1) 那会是.


Fel*_*ing 13

location对象具有pathname属性.

这将为您提供/questions/ask并删除第一个字符,使用substring(1):

var path = location.pathname.substring(1);
Run Code Online (Sandbox Code Playgroud)

  • @wamp:没有*更好*(无论如何你是什么意思?)。它们的工作方式不同。`substr` 将长度作为第二个参数,`substring` 是另一个索引(应提取字符串的索引)。在这种情况下,您使用哪个并不重要(我*假设*在内部它无论如何都是相同的功能)。 (2认同)