Use the Object.fromEntries method and pass the URLSearchParams instance as an argument. This creates a JavaScript object from the parsed query parameters: |
const params = Object.fromEntries( new URLSearchParams(window.location.search) ) // URL: example.com/path?foo=bar&name=futurestudio&num=1 // { foo: 'bar', name: 'futurestudio', num: '1' } |
Here’s how it works: the URLSearchParams class implements JavaScript’s iterator interface. The iterator interface contains the Iterator#entries method. This entries methods returns an iterator providing an array of [key, value] pairs: |
const params = new URLSearchParams('?foo=bar&name=futurestudio&num=1') const iterator = params.entries() iterator.next() // { done: false, value: ['foo', 'bar'] } iterator.next() // { done: false, value: ['name', 'futurestudio'] } iterator.next() // { done: false, value: ['num', '1] } iterator.next() // { done: true, value: undefined } |
Showing posts with label urlsearchparams. Show all posts
Showing posts with label urlsearchparams. Show all posts
Tuesday, February 7, 2023
Convert URLSearchParams to a JavaScript Object | JavaScript jQuery Get Parameters from URL | Get Params from URL using JavaScript
Subscribe to:
Posts (Atom)