Keywords: JavaScript | URL | Parameter Parsing | URLSearchParams | JSON.parse
Abstract: This article explores methods to convert URL query strings into JavaScript objects, covering traditional string manipulation with JSON.parse and modern approaches using URLSearchParams and Object.fromEntries. It includes code examples, comparisons, and handling of edge cases like encoding and duplicate keys.
Introduction
In web development, parsing URL query strings into JavaScript objects is a common task. For instance, given a string like abc=foo&def=%5Basf%5D&xyz=5, the goal is to convert it to an object such as { abc: 'foo', def: '[asf]', xyz: 5 }. This article discusses various methods to achieve this, from traditional approaches to modern APIs.
Traditional Method: String Replacement and JSON.parse
One historical method involves manipulating the string and using JSON.parse. The process includes decoding the URI, replacing delimiters, and constructing a JSON string. For example, starting with location.search.substring(1) which removes the leading '?', we can use:
var search = location.search.substring(1);
JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')This method works by transforming the string into a valid JSON format. However, it has limitations with special characters and encoding. An improved version uses a reviver function to handle decoding properly:
var search = location.search.substring(1);
JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key === "" ? value : decodeURIComponent(value) })This ensures that values are correctly decoded using decodeURIComponent.
Modern Method: URLSearchParams and Object.fromEntries
With the introduction of the URLSearchParams API in modern JavaScript, parsing URL parameters has become more straightforward. URLSearchParams provides methods to work with query strings. For example:
const params = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');
const obj = Object.fromEntries(params);
console.log(obj); // { abc: 'foo', def: '[asf]', xyz: '5' }URLSearchParams automatically handles percent-encoding and decoding. It is iterable, so it can be used with Object.fromEntries to directly create an object. This method is more robust and recommended for new projects.
Comparison and Best Practices
Both methods have their pros and cons. The traditional method is useful in environments without modern APIs but is error-prone with complex strings. The modern method using URLSearchParams is standardized and handles encoding correctly. However, note that URLSearchParams treats all values as strings, so if numerical values are needed, additional parsing is required. Also, by default, duplicate keys are not preserved; the last value wins. For handling multiple values, custom logic is needed, as shown in other answers.
Best practices include using URLSearchParams when possible, ensuring proper encoding, and testing with edge cases like empty values or special characters.
Conclusion
Parsing URL parameters to JavaScript objects can be done efficiently using modern APIs like URLSearchParams. While traditional methods work, they are less reliable. Developers should adopt the standard approaches for better maintainability and compatibility.