如何使用 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/