我有一个带有一些GET参数的URL,如下所示:

www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 

我需要得到c的全部值。我试图读取URL,但只得到m2。如何使用JavaScript执行此操作?


当前回答

对于像index.html这样的单参数值?msg=1使用以下代码,

$(window).load(function(){
    queryString();
});

function queryString()
{
    var queryString = window.location.search.substring(1);
    var varArray = queryString.split("="); //eg. index.html?msg=1

    var param1 = varArray[0];
    var param2 = varArray[1];

}

对于所有参数值,请使用以下代码:,

$(window).load(function(){
    queryString();
});

function queryString()
{
    var queryString = window.location.search;
    var varArray = queryString.split("&");
    for (var i=0;i<varArray.length;i++) {
      var param = varArray[i].split("=");
        //parameter-value pair
    }
} 

其他回答

我的解决方案:

/**
 * get object with params from query of url
 */
const getParams = (url) => {
  const params = {};
  const parser = document.createElement('a');
  parser.href = url;
  const query = parser.search.substring(1);
  if (query !== '') {
    const vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
      const pair = vars[i].split('=');
      const key = decodeURIComponent(pair[0]).replace('[]', '');
      const value = decodeURIComponent(pair[1]);
      
      if (key in params) {
        if (Array.isArray(params[key])) {
          params[key].push(value);
        } else {
          params[key] = [params[key]];
          params[key].push(value);
        }
      } else params[key] = value;
    }
  }
  return params;
}

我们可以以更简单的方式获取c参数值,而不必循环所有参数,请参见下面的jQuery获取参数。

1.获取参数值:

var url = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5";

url.match(**/(c=)[0-9A-Za-z-]+/ig**)[0].replace('c=',"")

(or)

url.match(**/(c=)[0-z-]+/ig**)[0].replace('c=',"")

以字符串形式返回

“m2-m3-m4-m5”

2.要替换参数值:

var url = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5";

url.replace(**/(c=)[0-9A-Za-z-]+/ig, "c=m2345"**)

以下是用于将url查询参数解析为Object的angularJs源代码:

函数tryDecodeURIComponent(值){尝试{返回decodeURIComponent(value);}捕获(e){//忽略任何无效的uri组件}}函数isDefined(value){return typeof value!==“undefined”;}函数parseKeyValue(keyValue){keyValue=keyValue.replace(/^\?/,“”);var obj={},key_value,key;var iter=(keyValue||“”).split('&');对于(var i=0;i<iter.length;i++){var kV值=iter[i];if(kV值){key_value=kV值。替换(/\+/g,“%20”)。拆分(“=”);key=tryDecodeURIComponent(key_value[0]);if(isDefined(键)){var val=isDefined(key_value[1])?tryDecodeURIComponent(key_value[1]):true;if(!hasOwnProperty.call(obj,key)){obj[key]=val;}else-if(isArray(obj[key])){obj[key].push(val);}其他{obj[key]=[obj[key],val];}}}};返回obj;}警报(JSON.stringify(parseKeyValue('?a=1&b=3&c=m2-m3-m4-m5')));

您可以将此函数添加到window.location:

window.location.query = function query(arg){
  q = parseKeyValue(this.search);
  if (!isDefined(arg)) {
    return q;
  }      
  if (q.hasOwnProperty(arg)) {
    return q[arg];
  } else {
    return "";
  }
}

// assuming you have this url :
// http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5

console.log(window.location.query())

// Object {a: "1", b: "3", c: "m2-m3-m4-m5"}

console.log(window.location.query('c'))

// "m2-m3-m4-m5"

ECMAScript 6解决方案:

var params = window.location.search
  .substring(1)
  .split("&")
  .map(v => v.split("="))
  .reduce((map, [key, value]) => map.set(key, decodeURIComponent(value)), new Map())

以下是我所做的:

var uriParams = getSearchParameters();
alert(uriParams.c);


// background functions:

// Get object/associative array of URL parameters
function getSearchParameters () {
  var prmstr = window.location.search.substr(1);
  return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}

// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
  var params = {},
      prmarr = prmstr.split("&");

  for (var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
  }
  return params;
}