Home > Article > Web Front-end > How to Convert URL Parameters to a JavaScript Object Efficiently?
In this modern era, it's essential to revisit the traditional methods of converting URL parameters to JavaScript objects. While some methods retain relevance, new approaches have emerged that offer improved efficiency and applicability.
One such approach is represented by the following snippet:
JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })
This method takes advantage of JSON's ability to handle escaped characters and allows for a wider range of characters in the search string. It additionally provides a reviver function that decodes URI-encoded values.
For example, parsing a search string like "abc=foo&def=[asf]&xyz=5&foo=b=ar" using this method yields:
Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}
The above is the detailed content of How to Convert URL Parameters to a JavaScript Object Efficiently?. For more information, please follow other related articles on the PHP Chinese website!