使用JS从url获取变量

时间:2013-01-11 16:24:31

标签: javascript jquery regex

  

可能重复:
  How can I get query string values?

我有这个链接

URL / merchant.html?ID = 45

我正在尝试使用JS或JQuery获取ID而没有运气。

我试过这段代码

var urlParams = {};
(function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

返回“undefined”

代码有什么问题?

2 个答案:

答案 0 :(得分:1)

在此处使用:

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

所以在你的情况下:

getParameterByName("id")

自: How can I get query string values in JavaScript?

答案 1 :(得分:0)

我写了这个函数一段时间了:

/**
 * Retrieves the value of a query string parameter.
 * @param string href The full URL
 * @param string key The key in the query string to search for.
 * @param variant def The default value to return if the key doesn't exist.
 * @returns variant if key exists returns the value, otherwise returns a default value.
 */
function getURIParam(href, key, def) {
    if (arguments.length == 2) def = null;
    var qs = href.substring(href.indexOf('?') + 1);
    var s = qs.split('&');
    for (var k in s) {
        var s2 = s[k].split('=');
        if (s2[0] == key)
            return decodeURIComponent(s2[1]);
    }
    return def;
}

您可以这样使用它:

var href = "http://www.example.org?id=1492";
var id = getURIParam(href, "id", 0);
//Output of id: 1492

如果密钥不存在:

var href = "http://www.example.org?id=1492";
var name = getURIParam(href, "name", "Unnamed");
//Output of name: Unnamed