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

How to Convert URL Parameters to a JavaScript Object Efficiently?

DDD
Release: 2024-11-05 07:53:02
Original
406 people have browsed it

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) })
Copy after login

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"}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template