我有一个带有一些GET参数的URL,如下所示:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要得到c的全部值。我试图读取URL,但只得到m2。如何使用JavaScript执行此操作?
我有一个带有一些GET参数的URL,如下所示:
www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
我需要得到c的全部值。我试图读取URL,但只得到m2。如何使用JavaScript执行此操作?
当前回答
您可以通过以下函数实现:
function getParameter(parameterName){
let paramsIndex = document.URL.indexOf("?");
let params="";
if(paramsIndex>0)
params=document.URL.substring(paramsIndex+1, document.URL.length).split("&");
let result = [];
for(let i=0;i<params.length;i++)
{
console.warn(params[i].split("=")[0].toString()+ "," + params[i].split("=")[1].toString());
var obj = {"key":params[i].split("=")[0].toString(),"value":params[i].split("=")[1].toString()};
result.push(obj);
}
return passedValue = result.find(x=>x.key==parameterName).value;
}
现在您可以使用getParameter(“parameterName”)获取参数值
其他回答
我做了一个函数来实现这一点:
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, {})
您可以添加一个输入框,然后要求用户将值复制到其中……这非常简单:
<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参数名作为关键字的对象,然后我们可以通过其名称轻松提取参数:
// URL: https://example.com/?test=true&orderId=9381
// Build an object containing key-value pairs
export const queryStringParams = window.location.search
.split('?')[1]
.split('&')
.map(keyValue => keyValue.split('='))
.reduce<QueryStringParams>((params, [key, value]) => {
params[key] = value;
return params;
}, {});
type QueryStringParams = {
[key: string]: string;
};
// Return URL parameter called "orderId"
return queryStringParams.orderId;
这是一个我觉得更可读的解决方案,但它需要一个.forEach()填充程序,用于<IE8:
var getParams = function () {
var params = {};
if (location.search) {
var parts = location.search.slice(1).split('&');
parts.forEach(function (part) {
var pair = part.split('=');
pair[0] = decodeURIComponent(pair[0]);
pair[1] = decodeURIComponent(pair[1]);
params[pair[0]] = (pair[1] !== 'undefined') ?
pair[1] : true;
});
}
return params;
}
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] =>
)*/