【发布时间】:2015-03-17 15:07:24
【问题描述】:
我正在尝试使用 JavaScript 或 jQuery 从当前 url 获取参数。 网址如下所示:
http://my-site.com/index.html#/?id=1426591453147
或
http://my-site.com/#/?id=1426591453147
我尝试了一些带有“location.search”的代码,但 location.search 在我的网址上返回一个空字符串。
有人知道解决这个问题的好方法吗?
编辑: 我最终使用了这个:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?]" + name + "=([^&#]*)"),
results = regex.exec(location.hash);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
【问题讨论】:
-
location.search适用于 URL 格式为:example.com?foo=bar。但是您的“查询字符串”以#开头,因此,字符串的其余部分使用location.hash访问。 -
"http://my-site.com/index.html#/?id=1426591453147".replace(/^.*?\.com(.*?)$/i, '$1') -
我最终使用了 zvonas 的答案。谢谢!
标签: javascript jquery url web parameters