我有一个带有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实现这一点?
我非常喜欢尽可能使用速记:
网址:example.com/mortgage_calc.htm?pmts=120&intr=6.8&prin=10000
纯Javascript:
for ( var vObj = {}, i=0, vArr = window.location.search.substring(1).split('&');
i < vArr.length; v = vArr[i++].split('='), vObj[v[0]] = v[1] ){}
// vObj = {pmts: "120", intr: "6.8", prin: "10000"}
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5";
var url = new URL(url_string);
let obj = {};
var c = url.searchParams.forEach((value, key) => {
obj[key] = value;
});
console.log(obj);
PHP的parse_str
函数模仿者.. :)
// 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] =>
)*/
我发现下面这个解决方案更易读一些——但是需要为< IE8添加一个.forEach()
的shim:
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;
}
function getParams(url){
var paramsStart = url.indexOf('?');
var params = null;
//no params available
if(paramsStart != -1){
var paramsString = url.substring(url.indexOf('?') + 1, url.length);
//only '?' available
if(paramsString != ""){
var paramsPairs = paramsString.split('&');
//preparing
params = {};
var empty = true;
var index = 0;
var key = "";
var val = "";
for(i = 0, len = paramsPairs.length; i < len; i++){
index = paramsPairs[i].indexOf('=');
//if assignment symbol found
if(index != -1){
key = paramsPairs[i].substring(0, index);
val = paramsPairs[i].substring(index + 1, paramsPairs[i].length);
if(key != "" && val != ""){
//extend here for decoding, integer parsing, whatever...
params[key] = val;
if(empty){
empty = false;
}
}
}
}
if(empty){
params = null;
}
}
}
return params;
}
简化版本,已测试
function get(name){
var r = /[?&]([^=#]+)=([^&#]*)/g,p={},match;
while(match = r.exec(window.location)) p[match[1]] = match[2];
return p[name];
}
usage:
var parameter = get['parameter']
require(["dojo/io-query"], function(ioQuery){
var uri = "www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5 ";
var query = uri.substring(uri.indexOf("?") + 1, uri.length);
var queryObject = ioQuery.queryToObject(query);
console.log(queryObject.c); //prints m2-m3-m4-m5
});
尝试
url.match(/[?&]c=([^&]*)/)[1]
var url = "www.test.com/t.html?a=1&bc=3&c=m2-m3-m4-m5";
c= url.match(/[?&]c=([^&]*)/)[1];
console.log(c);
这是Daniel Sokolowski在2019年6月27日的回答的改进版。正则表达式的解释如下:
[?&]
匹配的第一个字符必须是 ?
或 &
(忽略像 ac=
这样的参数)c=
参数名称以 =
结尾(...)
匹配第一个组[^&]*
与 &
不同的零个或多个字符(*
)[1]
从匹配数组中选择第一个组function getQueryParameter(query, parameter) {
return (window.location.href.split(parameter + '=')[1].split('&')[0]);}
const url = 'http://www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';
const params = [... new URL(url).searchParams.entries()]
.reduce((a, c) => Object.assign(a, {[c[0]]:c[1]}), {})
console.log(params);