How to Convert Url Parameters to a JavaScript Object

How to convert URL parameters to a JavaScript object?

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,"\":\"")) + '"}')

How to serialize an Object into a list of URL query parameters?

var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}

Example: http://jsfiddle.net/WFPen/

How to convert URL parameters to a JavaScript object?

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,"\":\"")) + '"}')

Convert javascript object to URL parameters

You should check this jQuery.param function.

var params = { width:1680, height:1050 };var str = jQuery.param( params );console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to convert Javascript object to a url string?

You can use array#map and join()

var obj = {name: "Omer",age: 30,siblings: 3};
var str = Object .keys(obj) .map(k => k + '=' + obj[k]) .join('&');
console.log(str);

Query-string encoding of a Javascript Object

like this?

serialize = function(obj) {  var str = [];  for (var p in obj)    if (obj.hasOwnProperty(p)) {      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));    }  return str.join("&");}
console.log(serialize({ foo: "hi there", bar: "100%"}));// foo=hi%20there&bar=100%25

Convert URL query parameters to object - preserve type?

There is no other way.

_urlToVideoOptions: function(url) {
var queryParameters = url.search.substr(1);

var videoOptions = {};
queryParameters.split('&').forEach(function(part) {
var item = part.split('=');
var val = decodeURIComponent(item[1]);
if (val == "true" || val == "false")
val = !!val;
else if (!isNaN(val)) {
if (val.indexOf('.') != -1)
val = parseFloat(val);
else
val = parseInt(val);
}
videoOptions[item[0]] = val;
});

return videoOptions;
}


Related Topics



Leave a reply



Submit