JavaScript - 如何解析 url 中的哈希参数?

标签 javascript

如何使用 js 获取 URL 哈希的一部分?

这是我所拥有的:

something.html?il=#/new/product/123

我需要将“123”作为变量......

***没有库,请使用纯 JavaScript。

有什么想法吗?

最佳答案

您需要哈希,而不是查询字符串。 # 之后的任何内容都称为 url 的哈希值。

您可以使用 document.location.hash 并解析该字符串

var id = document.location.hash.split("/"); //convert the hash into an array, splitting with "/"
id = id.pop(); //pop will get the last item on the array

无论此方法多么可读且简单,假设您正在搜索的字符串始终是数组中的最后一个是不安全的。您可以使用正则表达式来进一步缩小机会

var hash = document.location.hash,
    re = /\/new\/product\/(d+)/,
    id = hash.match(re);// for some reason this matches both the full string and the number
id = id.pop(); // so I must do this again

关于JavaScript - 如何解析 url 中的哈希参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16046252/

相关文章:

javascript - addEventListener() 不适用于元素列表

javascript - 简单的 jQuery - 命名函数然后调用它

javascript - Angularjs 下拉验证不起作用

Javascript对象获取上面的值

javascript - AngularJS中的两级层次结构中继器,第一级没有任何输出

javascript - 参数与 javascript 默认方法同名

javascript - 如何使用 rxjs 取消内部可观察计时器?

javascript - 如何使用 HTML 创建母版页?

javascript - 使用 Node 解析 XLSX 并创建 json

javascript - 在 Javascript 中复制和裁剪图像