How to get all query string parameters as an object in JavaScript
Answers
-
In JavaScript, you can use the
URLSearchParams
interface to convert a query string into an object. It provides utility methods to work with the query string of a URL.- Pass the query string to the
URLSearchParams
constructor to turn it into an object instance. - Use the
get()
method to access query string parameters. - To get a native JavaScript object, pass the object instance to the
Object.fromEntries()
method.
const qs = `?size=M&price=29&sort=desc` const params = new URLSearchParams(qs) console.log(params.get('size')) // M console.log(params.get('price')) // 29 console.log(params.get('sort')) // desc // Convert to native JS object const obj = Object.fromEntries(params) console.log(obj) // { size: 'M', price: '29', sort: 'desc' }
1 - Pass the query string to the
Howdy, Stranger!
Categories
- 94 All Categories
- 20 VoIP
- 7 SIP
- 16 asterisk
- 44 Programming
- 1 Nodejs
- 4 javascript
- 19 PHP
- 8 Codeigniter
- 14 database
- 1 UI/UX
- 2 Flutter
- 28 OS
- 26 Linux
- 1 Virtualization
- 1 Android
- 1 Windows
- 2 legal