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

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

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


当前回答

简单的方法

function getParams(url){
        var regex = /[?&]([^=#]+)=([^&#]*)/g,
            params = {},
            match;
        while(match = regex.exec(url)) {
            params[match[1]] = match[2];
        }
        return params;
    }

然后像getParams(url)一样调用它

其他回答

这是一种只检查一个参数的简单方法:

示例URL:

http://myserver/action?myParam=2

Javascript示例:

var myParam = location.search.split('myParam=')[1]

如果URL中存在“myParam”。。。变量myParam将包含“2”,否则将未定义。

在这种情况下,可能需要一个默认值:

var myParam = location.search.split('myParam=')[1] ? location.search.split('myParam=')[1] : 'myDefaultValue';

更新:这更有效:

var url = "http://www.example.com/index.php?myParam=384&login=admin"; // or window.location.href for current url
var captured = /myParam=([^&]+)/.exec(url)[1]; // Value is in [1] ('384' in our case)
var result = captured ? captured : 'myDefaultValue';

即使URL中充满了参数,它也能正常工作。

这是有效的:

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

我没有得到任何其他最好的答案。

我做了一个函数来实现这一点:

var getUrlParams = function (url) {
  var params = {};
  (url + '?').split('?')[1].split('&').forEach(function (pair) {
    pair = (pair + '=').split('=').map(decodeURIComponent);
    if (pair[0].length) {
      params[pair[0]] = pair[1];
    }
  });
  return params;
};

2017年5月26日更新,这里有一个ES7实现(使用babel预设阶段0、1、2或3运行):

const getUrlParams = url => `${url}?`.split('?')[1]
  .split('&').reduce((params, pair) =>
    ((key, val) => key ? {...params, [key]: val} : params)
    (...`${pair}=`.split('=').map(decodeURIComponent)), {});

一些测试:

console.log(getUrlParams('https://google.com/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('/foo?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('?a=1&b=2&c')); // Will log {a: '1', b: '2', c: ''}
console.log(getUrlParams('https://google.com/')); // Will log {}
console.log(getUrlParams('a=1&b=2&c')); // Will log {}

2018年3月26日更新,这里是一个Typescript实现:

const getUrlParams = (search: string) => `${search}?`
  .split('?')[1]
  .split('&')
  .reduce(
    (params: object, pair: string) => {
      const [key, value] = `${pair}=`
        .split('=')
        .map(decodeURIComponent)

      return key.length > 0 ? { ...params, [key]: value } : params
    },
    {}
  )

2019年2月13日更新,这里是一个与TypeScript 3一起使用的更新的TypeScript实现。

interface IParams { [key: string]: string }

const paramReducer = (params: IParams, pair: string): IParams => {
  const [key, value] = `${pair}=`.split('=').map(decodeURIComponent)

  return key.length > 0 ? { ...params, [key]: value } : params
}

const getUrlParams = (search: string): IParams =>
  `${search}?`.split('?')[1].split('&').reduce<IParams>(paramReducer, {})

以下是用于将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"

获取单个参数值:

function getQueryParameter(query, parameter) {
return (window.location.href.split(parameter + '=')[1].split('&')[0]);}