window.location.search查询为JSON

有没有更好的方法将URL的location.search转换为对象? 也许只是更高效或减少? 我正在使用jQuery,但纯JS也可以使用。

var query = window.location.search.substring(1), queryPairs = query.split('&'), queryJSON = {}; $.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; }); 

这是一个纯JS函数。 解析当前URL的搜索部分并返回一个对象。 (对于可读性而言,它有点冗长。)

 function searchToObject() { var pairs = window.location.search.substring(1).split("&"), obj = {}, pair, i; for ( i in pairs ) { if ( pairs[i] === "" ) continue; pair = pairs[i].split("="); obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] ); } return obj; } 

在相关的说明中,您不是试图将单个参数存储在“一个JSON”中,而是存储在“一个对象”中。 ;)

如果您使用的是现代浏览器,则会产生与接受的答案相同的结果:

 function searchToObject(search) { return search.substring(1).split("&").reduce(function(result, value) { var parts = value.split('='); if (parts[0]) result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); return result; }, {}) } 

对于简单案例,可能是最短的解决方案:

 location.search .slice(1) .split('&') .map(p => p.split('=')) .reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); 

我的方法,简单而干净

 var params = "?q=Hello World&c=Awesome"; params = "{\"" + params .replace( /\?/gi, "" ) .replace( /\&/gi, "\",\"" ) .replace( /\=/gi, "\":\"" ) + "\"}"; params = JSON.parse( params ); alert( decodeURIComponent( params.q ) ); alert( decodeURIComponent( params.c ) ); 

只是想使用一点ESNext和一个reducer来分享这个解决方案。

它与@Carlo的建议几乎完全相同,但如果你对ES6和减速器感到满意,它会更加清晰。

 const urlSearchData = searchString => { if (!searchString) return false; return searchString .substring(1) .split('&') .reduce((result, next) => { let pair = next.split('='); result[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); return result; }, {}); }; const searchData = urlSearchData(window.location.search); 

在@ rafaelbiten的ES6工作的基础上,我添加了对没有值的参数的支持以及重复输入样式的查询参数数组。

JSFiddle: https ://jsfiddle.net/w922xefs/

 const queryStringToJSObject = searchString => { if (!searchString) return null; return searchString .replace(/^\?/, '') // Only trim off a single leading interrobang. .split('&') .reduce((result, next) => { if (next === "") { return result; } let pair = next.split('='); let key = decodeURIComponent(pair[0]); let value = typeof pair[1] !== "undefined" && decodeURIComponent(pair[1]) || undefined; if (result.hasOwnProperty(key)) { // Check to see if this property has been met before. if (Array.isArray(result[key])) { // Is it already an array? result[key].push(value); } else { // Make it an array. result[key] = [result[key], value]; } } else { // First time seen, just add it. result[key] = value; } return result; }, {} ); }; // Simple read of query string const searchData = queryStringToJSObject(window.location.search); 

stringify之后的JSON Parse完成了使用数组数据转换为json的工作。

?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&

 { 'key1' : 'val1', 'key2' : [ 'val2.1', 'val2.2', 'val2.3' ] } 
 function QueryParamsToJSON() { var list = location.search.slice(1).split('&'), result = {}; list.forEach(function(keyval) { keyval = keyval.split('='); var key = keyval[0]; if (/\[[0-9]*\]/.test(key) === true) { var pkey = key.split(/\[[0-9]*\]/)[0]; if (typeof result[pkey] === 'undefined') { result[pkey] = []; } result[pkey].push(decodeURIComponent(keyval[1] || '')); } else { result[key] = decodeURIComponent(keyval[1] || ''); } }); return JSON.parse(JSON.stringify(result)); } var query_string = QueryParamsToJSON(); 

注意 –毫无疑问上述解决方案有效,但它不会涵盖所有运营商

猜猜你会想要这样的东西 –

 var search = location.search; var trimmedSearch = search.substring(1); var searchObj = trimmedSearch?JSON.parse( '{"' + trimmedSearch.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) } ) : {} console.log(searchObj); 

前 –

用@覆盖搜索@第1行

 search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar"; 

你得到的输出是

 Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"} 

如果有人想要访问搜索查询参数,请使用此function:

 function getQueryStringValue (key) { return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")) } 

易于使用只需调用getQueryStringValue(term)