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
Window.Onload VS <Body Onload=""/>
How to Move Cursor to End of Contenteditable Entity
Promise.All: Order of Resolved Values
Get Elements by Attribute When Queryselectorall Is Not Available Without Using Libraries
When Should I Use Jquery's Document.Ready Function
How to Customize Object Equality for JavaScript Set
After Calling Chrome.Tabs.Query, the Results Are Not Available
Passing Custom Props to Router Component in React-Router V4
How to Quickly and Conveniently Disable All Console.Log Statements in My Code
React Onclick Function Fires on Render
How to Use JavaScript to Change the Meta-Tags of the Page
Declaring Variables Without Var Keyword
How to Strip HTML Tags from String in JavaScript
Pass a Parameter to a Content Script Injected Using Chrome.Tabs.Executescript()
The Value of "This" Within the Handler Using Addeventlistener