How to get anything following the domain in a url, using Javascript

六眼飞鱼酱① 提交于 2019-12-24 08:37:57

问题


What is the best way to get the "anything" part after the domain part, using Javascript:

http://www.domain.com/anything
http://www.domain.com/#anything
http://www.domain.com/any/thing

For http://www.domain.com/#anything I would have to use window.location.hash. But for http://www.domain.com/anything I would have to use window.location.pathname.

I'm using:

window.location.href.replace(window.location.origin, "").slice(1)

Are there any caveats with this solution? Is there a better way?


回答1:


Caveats:
location.origin is not supported by IE.
Other improvements: .slice is actually calling Array.prototype.slice. A method call that requires a prototype lookup is bound to be slower than accessing the element you need directly, escpeciallly in your case, where the slice method is returning an array with just 1 element anyway. So:

You could use location.pathname, but be weary: the standard reads:

pathname
This attribute represents the path component of the Location's URI which consists of everything after the host and port up to and excluding the first question mark (?) or hash mark (#).

but I think the easiest, most X-browser way of getting what you want is actually simply doing this:

var queryString = location.href.split(location.host)[1];
//optionally removing the leading `/`
var queryString = location.href.split(location.host)[1].replace(/^\//,'');

It's very similar to what you have now, except for the fact that I'm not using location.origin, which, as shown on MDN is not supported by MS's IE...
Another benefit is that I'm not calling Array.prototype.slice, which returns an array, and requires a prototype-lookup, which is marginally slower, too...




回答2:


window.location.pathname + window.location.search + window.location.hash

I think this one is a little bit better. You dont have to use any functions here...



来源:https://stackoverflow.com/questions/19112442/how-to-get-anything-following-the-domain-in-a-url-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!