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

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

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


当前回答

这里是一个递归解决方案,它没有正则表达式,并且具有最小的变异(只有params对象被变异,我认为这在JS中是不可避免的)。

太棒了,因为它:

是递归的处理多个同名参数处理格式错误的参数字符串(缺少值等)如果“=”在值中,则不中断执行URL解码最后,这太棒了,因为它……啊!!!

代码:

var get_params = function(search_string) {

  var parse = function(params, pairs) {
    var pair = pairs[0];
    var parts = pair.split('=');
    var key = decodeURIComponent(parts[0]);
    var value = decodeURIComponent(parts.slice(1).join('='));

    // Handle multiple parameters of the same name
    if (typeof params[key] === "undefined") {
      params[key] = value;
    } else {
      params[key] = [].concat(params[key], value);
    }

    return pairs.length == 1 ? params : parse(params, pairs.slice(1))
  }

  // Get rid of leading ?
  return search_string.length == 0 ? {} : parse({}, search_string.substr(1).split('&'));
}

var params = get_params(location.search);

// Finally, to get the param you want
params['c'];

其他回答

我尝试了很多不同的方法,但当我在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米

浏览器供应商已经通过URL和URLSearchParams实现了一种本地方式。

let url = new URL('http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5');
let searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('c'));  // outputs "m2-m3-m4-m5"

目前支持Firefox、Opera、Safari、Chrome和Edge。有关浏览器支持的列表,请参阅此处。

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParamshttps://developer.mozilla.org/en-US/docs/Web/API/URL/URL

https://url.spec.whatwg.org/

谷歌工程师埃里克·比德尔曼(Eric Bidelman)建议在不受支持的浏览器上使用这种polyfill。

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

<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();

正如在最新浏览器的第一个答案中提到的,我们可以使用新的URL api,然而,获取对象中的所有参数并使用它们的更一致的本地javascript简单解决方案可能是

例如,该类表示locationUtil

const locationSearch = () => window.location.search;
const getParams = () => {
  const usefulSearch = locationSearch().replace('?', '');
  const params = {};
  usefulSearch.split('&').map(p => {
    const searchParam = p.split('=');
    const [key, value] = searchParam;
    params[key] = value;
    return params;
  });
  return params;
};

export const searchParams = getParams();

用法::现在可以在类中导入searchParams对象

url示例---https://www.google.com?key1=https://www.linkedin.com/in/spiara/&valid=true

import { searchParams } from '../somewhere/locationUtil';

const {key1, valid} = searchParams;
if(valid) {
 console.log("Do Something");
 window.location.href = key1;
}

使用URLSearchParams的超简单方法。

function getParam(param){
  return new URLSearchParams(window.location.search).get(param);
}

目前,Chrome、Firefox、Safari、Edge和其他浏览器都支持它。