本文介绍了如何使用Javascript在网址中获取域名之后的任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript在域部分之后获得任何"部分的最佳方法是什么:

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

对于 http://www.domain.com/#anything ,我必须使用 window.location.hash .但是对于 http://www.domain.com/anything ,我将不得不使用 window. location.pathname .

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.

我正在使用:

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

此解决方案有什么警告吗?有更好的方法吗?

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

推荐答案

注意事项:
IE不支持location.origin.
其他改进:.slice实际上正在调用Array.prototype.slice.需要原型查找的方法调用势必比直接访问您需要的元素要慢,尤其是在您的情况下,其中slice方法返回仅包含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:

您可以使用location.pathname,但会感到疲倦:标准内容为:

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

但是我认为最简单,最X的浏览器获取所需内容的方法实际上就是这样做:

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(/^\//,'');

它与您现在拥有的非常相似,除了我没有使用location.origin之外,location.origin ...
另一个好处是,我不调用Array.prototype.slice,它返回一个数组,并且需要原型查找,这也稍慢一些...

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...

这篇关于如何使用Javascript在网址中获取域名之后的任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:17