如何使用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
Run Code Online (Sandbox Code Playgroud)
无论此方法的可读性和简单性如何,假设您正在搜索的字符串始终是数组中的最后一个是不安全的。您可以使用正则表达式来进一步缩小机会
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26152 次 |
| 最近记录: |