clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Dealing with URL parameters in JavaScript

Filed under: JavaScript— Tagged with: URLs

How to extract parameters from a URL and how to make new URLs, the official way, without combining strings or using 3rd party dependencies.

Get params from URL

Get URL parameters from a URL in a form where you can easily process them further:

const myUrl = new URL('https://example.com?foo=bar&baz=fooz')
const params = [...myUrl.searchParams.entries()]

console.log(params)
// [["foo", "bar"], ["baz", "fooz"]]

The myUrl.searchParams.entries() returns an iterator, but you can turn it into an array by spreading it, or process it with a for..of loop, which handles iterators.

The searchParams method won’t give out objects, if that’s what you want, but you can make one with reduce:

const paramObject = params.reduce((acc, [key, value]) => {
  return { ...acc, [key]: value }
}, {})

console.log(paramObject) // { foo: "bar", baz: "fooz" }

Serialize params object

Data often come as an object or as an array from the database, but URLs are all strings. The URLSearchParams interface can be used to stringify and otherwise process the params data:

const searchParams = new URLSearchParams({ foo: 'bar', baz: 'fooz' })
const paramString = searchParams.toString()

console.log(paramString) // foo=bar&baz=fooz

Nested array works too:

const searchParams = new URLSearchParams([
  ['foo', 'bar'],
  ['baz', 'fooz']
])
const paramString = searchParams.toString()
console.log(paramString) // foo=bar&baz=fooz

This is the point where you’d append params:

const searchParams = new URLSearchParams({ foo: 'bar', baz: 'fooz' })
searchParams.append('corge', 'grault')
const paramString = searchParams.toString()

console.log(paramString) // foo=bar&baz=fooz&corge=grault

URLSearchParams has a ton of other methods, too.

See all methods
URLSearchParams.append()

Appends a specified key/value pair as a new search parameter.

URLSearchParams.delete()

Deletes the given search parameter, and its associated value, from the list of all search parameters.

URLSearchParams.entries()

Returns an iterator allowing iteration through all key/value pairs contained in this object in the same order as they appear in the query string.

URLSearchParams.forEach()

Allows iteration through all values contained in this object via a callback function.

URLSearchParams.get()

Returns the first value associated with the given search parameter.

URLSearchParams.getAll()

Returns all the values associated with a given search parameter.

URLSearchParams.has()

Returns a boolean value indicating if such a given parameter exists.

URLSearchParams.keys()

Returns an iterator allowing iteration through all keys of the key/value pairs contained in this object.

URLSearchParams.set()

Sets the value associated with a given search parameter to the given value. If there are several values, the others are deleted.

URLSearchParams.sort()

Sorts all key/value pairs, if any, by their keys.

URLSearchParams.toString()

Returns a string containing a query string suitable for use in a URL.

URLSearchParams.values()

Returns an iterator allowing iteration through all values of the key/value pairs contained in this object.

Make new URL with params

Above we made the params, but not the full URL. We can use the URL helper to do that:

const url = new URL('https://example.com')
const paramObj = { foo: 'bar', baz: 'fooz' }
Object.keys(paramObj).forEach(key => url.searchParams.set(key, paramObj[key]))

console.log(url.href) // https://example.com/?foo=bar&baz=fooz

Conclusions

It’s good that the URL helpers have been widely supported already for a good while now. Where as before we needed to use external helpers like qs, which is about 30kB in size (it also does a lot more though, and has its use-case for sure), or construct URLs with template strings or concatenating with the + operator, what a hassle.

Hope this was helpful, thanks for reading!

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @intterne if you want to make a correction etc.

  • © 2022 Antti Hiljá
  • About
  • Follow my new Twitter account → @intterne
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!