Read more

JavaScript: Working with Query Parameters

Julian
March 03, 2022Software engineer at makandra GmbH

tl;dr: Use the URLSearchParams API to make your live easier if you want to get or manipulate query parameters (URL parameters).

URLSearchParams API

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

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 07:58)