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

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

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


当前回答

正如在最新浏览器的第一个答案中提到的,我们可以使用新的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;
}

其他回答

我使用

function getVal(str) {
    var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
    return v ? v[1] : null;
}
function parseUrl(url){
    let urlParam = url.split("?")[1];
    console.log("---------> URL param : " + urlParam);
    urlParam = urlParam.split("&");
    let urlParamObject = {};
    for(let i=0;i < urlParam.length;i++){
        let tmp = urlParam[i].split("=");
        urlParamObject[tmp[0]] = tmp[1];
    }
    return urlParamObject;
}

let param = parseUrl(url);
param.a // output 10
param.b // output 20

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

function getParamValue(param) {
    var urlParamString = location.search.split(param + "=");
    if (urlParamString.length <= 1) return "";
    else {
        var tmp = urlParamString[1].split("&");
        return tmp[0];
    }
}

无论参数是否为最后一个,这都适用于您的情况。

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] =>
)*/