Question:
Given a URL parameter string, such as "abc=foo&def=[asf]&xyz=5," how can we efficiently convert it into a JavaScript object?
Answer:
One of the most convenient and reliable methods to achieve this is by leveraging the power of JSON.parse(). However, to make this process compatible with URL parameters, we need to perform a few transformations first:
Here's an example implementation:
<code class="javascript">const urlParams = "abc=foo&def=%5Basf%5D&xyz=5"; const decodedParams = decodeURI(urlParams); const escapedQuotes = decodedParams.replace(/"/g, '\"'); const commaSeparated = escapedQuotes.replace(/&/g, '","'); const colonSeparated = commaSeparated.replace(/=/g, '":"'); const jsonReady = `{"` + colonSeparated + `"}`; const jsonObject = JSON.parse(jsonReady); console.log(jsonObject); // { abc: 'foo', def: '[asf]', xyz: 5 }</code>
By following these steps, you can seamlessly convert URL parameters into a JavaScript object, making it easy to access and manipulate the data programmatically.
The above is the detailed content of How to Efficiently Convert URL Parameters to a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!