javascript - 如何使用 Javascript 获取 url 中域之后的任何内容

标签 javascript url hash window.location

使用 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

我正在使用:

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

此解决方案有任何注意事项吗?有没有更好的办法?

最佳答案

注意事项:
IE 不支持 location.origin
其他改进:.slice 实际上是在调用Array.prototype.slice。需要原型(prototype)查找的方法调用必然比直接访问您需要的元素慢,尤其是在您的情况下, slice 方法返回的数组无论如何都只有 1 个元素。所以:

您可以使用 location.pathname,但要小心:标准内容如下:

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 (#).

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

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

它与您现在拥有的非常相似,除了我没有使用 location.originas shown on MDN MS的IE不支持...
另一个好处是我没有调用 Array.prototype.slice,它返回一个数组,并且需要一个原型(prototype)查找,这也稍微慢一些......

关于javascript - 如何使用 Javascript 获取 url 中域之后的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19112442/

相关文章:

iphone - 未安装的 App 的 URL Scheme

php - 如何为两个版本(移动版和桌面版)保持相同的 URL?

ruby - 如何将一组相似的哈希值限制为具有多个相同键 :value pair (details inside) 的哈希值

javascript - d3 分位数尺度分位数四舍五入

javascript - Angular HttpClient 不包含指定的 header

security - 引用 header 中的 CDN 和个人身份信息

java - 哈希表内部索引

javascript - 检查文件是否存在于不同的服务器上

javascript - 模态图片库 - 多张图片

带数字输出的 Python 256 位哈希函数