My question is about full power solution for parsing ANY complex URI parameters using just normal browser's Javascript. Like it do PHP, for simple code compatibility between JS and PHP sources.
But the first, let us see some particular known decisions:
1. There is popular question and answers on StackOverflow, see How can I get query string values in JavaScript?
You can find there quite simple solutions for common SIMPLE cases. For example, like handling this scalar parameters like this one:
https://example.com/?name=Jonathan&age=18
It has no answers for handling complex query params. (As far as I could see for answers with source codes and author comments)
2. Also you may use an URL object in modern browsers, see https://developer.mozilla.org/en-US/docs/Web/API/URL, or exactly https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams
It is enought powerful and you don't need to write or load any code for parsing URI parameters - just use
var params = (new URL(document.location)).searchParams;
var name = params.get("name"); // is the string "Jonathan"
var age = parseInt(params.get("age")); // is the number 18
This approach has such disadvantage that URL is available only in most of modern browsers, - other browsers or outdated versions of browsers will fail.
So, what I need. I need parsing any complex URI params, like
https://example.com/?a=edit&u[name]=Jonathan&u[age]=18&area[]=1&area[]=20&u[own][]=car&u[own][]=bike&u[funname]=O%27Neel%20mc%20Fly&empty=&nulparam&the%20message=Hello%20World
to
{
'a': 'edit',
'u': {
'name': 'Jonathan',
'age': '18',
'own': ['car', 'bike'],
'funname': 'O\'Neel mc Fly'
},
'area': [1, 20],
'empty': '',
'nulparam': null,
'the message': 'Hello World'
}
Preferrable answer is just plain readable javascript source. Simple and small wide-used library can be accepted too, but this question is not about them.
`
PS: To start I just publish my own current solution for parsing URI params and vice versa for making URI from params. Any comments for it are welcome.
Hope this helps to save time for lot of coders later.
A bit late, but just struggled over the same problem, solution was very simple:
use encodeURIComponent(...) for the stringified complex objects, the result can then be used as normal queryString-Part.
In the result-side the query-string-parameters have to be un-stringified.
Example:
My solution
Usage:
Code: