Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert URL parameters to a JavaScript object? [duplicate]

I have a string like this:

abc=foo&def=%5Basf%5D&xyz=5 

How can I convert it into a JavaScript object like this?

{   abc: 'foo',   def: '[asf]',   xyz: 5 } 
like image 347
Alex Avatar asked Dec 27 '11 20:12

Alex


People also ask

Can you use Javascript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.

What is URLSearchParams?

The URLSearchParams interface defines utility methods to work with the query string of a URL.


1 Answers

In the year 2021... Please consider this obsolete.

Edit

This edit improves and explains the answer based on the comments.

var search = location.search.substring(1); JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}') 

Example

Parse abc=foo&def=%5Basf%5D&xyz=5 in five steps:

  • decodeURI: abc=foo&def=[asf]&xyz=5
  • Escape quotes: same, as there are no quotes
  • Replace &: abc=foo","def=[asf]","xyz=5
  • Replace =: abc":"foo","def":"[asf]","xyz":"5
  • Suround with curlies and quotes: {"abc":"foo","def":"[asf]","xyz":"5"}

which is legal JSON.

An improved solution allows for more characters in the search string. It uses a reviver function for URI decoding:

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

Example

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

gives

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

Original answer

A one-liner:

JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}') 
like image 110
Wolfgang Kuehn Avatar answered Sep 23 '22 17:09

Wolfgang Kuehn