tl;dr: Use the URLSearchParams
API to make your live easier if you want to get or manipulate query parameters (URL parameters).
URLSearchParams
API
The URLSearchParams
API is
supported
Show archive.org snapshot
in all major browsers except IE 11.
It offers you a bunch of useful methods:
-
URLSearchParams.append()
- appends a query parameter -
URLSearchParams.delete()
- deletes the specified query parameter -
URLSearchParams.get()
- returns the value of the specified query parameter -
URLSearchParams.has()
- checks if specified query parameter exists -
URLSearchParams.set()
- sets the value to the specified query parameter - more Show archive.org snapshot
Example
const params = new URLSearchParams('foo=bar')
params.append('baz', 'baq')
params.toString() // 'foo=bar&baz=baq'
params.delete('baz')
params.toString() // 'foo=bar'
params.get('foo') // 'bar'
params.has('foo') // true
params.set('foo', 'baz')
params.toString() // 'foo=baz'
Working with URLs
You can also easily use the URLSearchParams
API if you have an URL
or an URL as string.
const urlString = 'https://makandracards.com/makandra/search?query=foo'
const url = new URL(urlString)
url.searchParams.get('query') // 'foo'
Posted by Julian to makandra dev (2022-03-03 06:58)