Home  >  Article  >  Web Front-end  >  How to Convert URL Parameters to a JavaScript Object Efficiently?

How to Convert URL Parameters to a JavaScript Object Efficiently?

DDD
DDDOriginal
2024-11-05 07:53:02311browse

How to Convert URL Parameters to a JavaScript Object Efficiently?

Converting URL Parameters to a JavaScript Object

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn