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

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

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


当前回答

我见过的大多数实现都错过了URL对名称和值的解码。

下面是一个通用的实用程序函数,它也可以进行正确的URL解码:

function getQueryParams(qs) {
    qs = qs.split('+').join(' ');

    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
}

//var query = getQueryParams(document.location.search);
//alert(query.foo);

其他回答

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

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, {})

PHP parse_str copycat..:)

// Handles also array params well
function parseQueryString(query) {
    var pars = (query != null ? query : "").replace(/&+/g, "&").split('&'),
        par, key, val, re = /^([\w]+)\[(.*)\]/i, ra, ks, ki, i = 0,
        params = {};

    while ((par = pars.shift()) && (par = par.split('=', 2))) {
        key = decodeURIComponent(par[0]);
        // prevent param value going to be "undefined" as string
        val = decodeURIComponent(par[1] || "").replace(/\+/g, " ");
        // check array params
        if (ra = re.exec(key)) {
            ks = ra[1];
            // init array param
            if (!(ks in params)) {
                params[ks] = {};
            }
            // set int key
            ki = (ra[2] != "") ? ra[2] : i++;
            // set array param
            params[ks][ki] = val;
            // go on..
            continue;
        }
        // set param
        params[key] = val;
    }

    return params;
}

var query = 'foo=1&bar=The+bar!%20&arr[]=a0&arr[]=a1&arr[s]=as&isset&arr[]=last';
var params = parseQueryString(query);
console.log(params)
console.log(params.foo)        // 1
console.log(params.bar)        // The bar!
console.log(params.arr[0])     // a0
console.log(params.arr[1])     // a1
console.log(params.arr.s)      // as
console.log(params.arr.none)   // undefined
console.log("isset" in params) // true like: isset($_GET['isset'])



/*
// in php
parse_str('foo=1&bar=The+bar!%20&arr[]=a0&arr[]=a1&arr[s]=as&isset&arr[]=last', $query);
print_r($query);

Array
(
    [foo] => 1
    [bar] => The bar!
    [arr] => Array
        (
            [0] => a0
            [1] => a1
            [s] => as
            [2] => last
        )

    [isset] =>
)*/

您可以添加一个输入框,然后要求用户将值复制到其中……这非常简单:

<h1>Hey User! Can you please copy the value out of the location bar where it says like, &m=2? Thanks! And then, if you could...paste it in the box below and click the Done button?</h1>
<input type='text' id='the-url-value' />
<input type='button' value='This is the Done button. Click here after you do all that other stuff I wrote.' />

<script>
//...read the value on click

好吧,但说真的。。。我发现了这段代码,它似乎很有用:

http://www.developerdrive.com/2013/08/turning-the-querystring-into-a-json-object-using-javascript/

function queryToJSON() {
    var pairs = location.search.slice(1).split('&');

    var result = {};
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });

    return JSON.parse(JSON.stringify(result));
}

var query = queryToJSON();

使用replace()方法的最简单方法:

从urlStr字符串:

paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');

或从当前URL:

paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');

说明:

document.URL-接口以字符串形式返回文档位置(页面URL)。replace()-方法返回一个新字符串,其中模式的部分或全部匹配项由替换项替换。/.*param_name=([^&]*).*/-括在斜杠之间的正则表达式模式,表示:.*-零个或多个字符,param_name=-已搜索的param名称,正则表达式中的()-组,[^&]*-一个或多个字符,不包括&,|-交替,$1-对正则表达式中第一个组的引用。

var urlStr='www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5’;var c=urlStr.replace(/.*c=([^&]*).*|(.*)/,'$1');var notExisted=urlStr.replace(/.*not_existed=([^&]*).*|(.*)/,'$1');console.log(`c==='${c}');console.log(`notExisted=='${notExisted}');

我尝试了很多不同的方法,但当我在URL中查找参数值时,这个尝试过的真正的正则表达式函数对我很有用,希望这有帮助:

var text='www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5'函数QueryString(项,文本){var foundString=text.match(新RegExp(“[\?\&]”+item+“=([^\&]*)(\&?)”,“i”));返回foundString?foundString[1]:foundString;}console.log(QueryString('c',文本));

使用类似QueuryString('param_name',url),并将返回值

平方米-3米-4米