queryObject
The queryObject
function parses a URL's query string into a structured JavaScript object. It supports nested objects, arrays, and automatic type conversion for numbers and booleans.
Examples
Basic Query Parsing
For a URL:
https://example.com?page_id=12&active=true&category=books&token=8b3a2ca1fa73n31e
window.location.queryObject();
// Output: { page_id: 12, active: true, category: "books",token:"8b3a2ca1fa73n31e" }
Nested Query Keys
For a URL:
https://example.com?user.name=John&user.age=30
window.location.queryObject();
// Output: { user: { name: 'John', age: 30 } }
Array Values
For a URL:
https://example.com?tags[]=js&tags[]=html&tags[]=css
window.location.queryObject();
// Output: { tags: ['js', 'html', 'css'] }
Combination of Nested and Arrays
For a URL:
https://example.com?user.hobbies[]=coding&user.hobbies[]=reading
window.location.queryObject();
// Output: { user: { hobbies: ['coding', 'reading'] } }
Malformed Query Handling
For a URL:
https://example.com?valid=true&malformed%
window.location.queryObject();
// Output: { valid: true }
// Logs: Malformed query string pair detected: "malformed%". It has been skipped.
Key Features
Automatic Type Conversion: Converts numbers (
123
→123
), booleans (true
→true
), and retains strings.Nested Key Support: Easily handles dot-separated keys (
user.name
).Array Support: Recognizes keys ending with
[]
as arrays.Graceful Degradation: Skips malformed query pairs with a warning.
Notes
Returns
null
if the query string is empty.Highly customizable for various URL query formats.
Last updated