0

I am trying to lowercase a query string and get the value even if the URL is with capital letters.

This is works - I can get the value:

 ?serialid=1234 

This does not work - I Cannot get the value (Capital S):

 ?Serialid=1234

I would like to match both cases.

My script:

 $(document).ready(function () {

     var a = getQueryString("serialid");
     $('#SerialIdHP').val(a);
 });

 function getQueryString(key) {

     var vars = [],
         hash;
     var hashes = (window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')).toString().toLowerCase();

     for (var i = 0; i < hashes.length; i++) {
         hash = hashes[i].split('=');
         vars.push(hash[0]);
         vars[hash[0]] = hash[1];
     }
     return vars[key];
 }
4

4 回答 4

3

用于toLowerCase()转换密钥

function getQueryString(url, key) {
    var vars = [],
        hash;
    var hashes = (url.slice(url.indexOf('?') + 1).split('&'));

    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0].toLowerCase());
        vars[hash[0].toLowerCase()] = hash[1];
    }
    return vars[key.toLowerCase()];
}

var url = "http://something.com?serialid=1234 "
var a = getQueryString(url, "SerialId");
alert(a);

演示:http: //jsfiddle.net/T9BsR/1/

于 2013-08-29T08:53:47.767 回答
0

一般来说,我反对您在这里尝试实现的方法,因为您应该准确地知道查询参数的名称(包括案例)。

无论如何,您正在寻找的答案是:

$(document).ready(function () {
    var a = getQueryString("serialid");
    $('#SerialIdHP').val(a);
});

function getQueryString(parameter) {
    var regex = new RegExp(parameter + "=([^&$]*)","i");
    var match = window.location.search.match(regex);
    return match ? match[1] : '';
}
于 2013-08-29T09:29:17.713 回答
0

这是一个更简单的函数,可以完成大部分繁重的工作。它检索对象中的查询变量:

function parseQuery(query) {

  var queryvars = {}
    , patt = /[?&]([^&]+)=([^&]+)/g;

  decodeURIComponent(query).replace(patt, function(_, key, val){
    queryvars[key.toLowerCase()] = val;
  });

  return queryvars;
}

var queryvars - parseQuery('?Serialid=1234');
//^ {
//    serialid: "1234"
//  }

queryvars将在键:值对中以小写形式包含来自 url 的所有变量。要访问变量并确保它始终为小写,您可以创建另一个帮助程序:

function getQueryVar(key, query) {
  return parseQuery(query)[key.toLowerCase()];
}

var serialid = getQueryVar('SerialID', window.location.search);
于 2013-08-29T08:55:34.707 回答
0
$(document).ready(function () {
    var a = getQueryString("serialid").toLowerCase();
    $('#SerialIdHP').val(a);
});

function getQueryString(key) {

    var vars = [],
        hash;
    var hashes = (window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')).toString().toLowerCase();

    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars[key];
}
于 2013-08-29T08:47:38.873 回答