从javascript中的url获取查询字符串

从javascript中的url获取查询字符串,javascript,query-string,Javascript,Query String,我一直在尝试使用javascript从url获取查询字符串 我正在使用以下代码 function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search

我一直在尝试使用javascript从url获取
查询字符串

我正在使用以下代码

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function() {
    prodId = getParameterByName('id');
    prodName = getParameterByName('name');
});
它适用于URL,如
http://my_ip/main.html?id=123&name=test


但是当URL像
http://192.168.0.216:1009/main.html#!/video.html?id=123&name=test
失败,为
prodID
prodName
提供空字符串问题在于
http://192.168.0.216:1009/main.html#!/video.html?id=123&name=test
没有
位置。search
部分。它有
location.hash
-在
#
字符之后的所有内容

您可以做的一件简单的事情是修改函数,使其也能够使用location.hash。例如:

function getParameterByName(name, useHash) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location[useHash ? 'hash' : 'search']);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var prodId = getParameterByName('id', true); // true - use location.hash for "query parameters"
然后像这样使用它:

function getParameterByName(name, useHash) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location[useHash ? 'hash' : 'search']);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var prodId = getParameterByName('id', true); // true - use location.hash for "query parameters"

为我工作。检查查询字符串必须在哈希之前。URL应该是
http://192.168.0.216:1009/main.html?id=123&name=test#!/video.html
@Barmar OP可能使用了一些SPA框架,其中模拟了如下查询字符串。如果要将
#
作为路径名的一部分,他可能需要对其进行URL编码。