# Dealing with URL parameters in JavaScript/TypeScript

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:

```ts
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](/iterators), but you
can turn it into an array by spreading it, or process it with a
[for..of loop](/the-new-es6-for-of-loop-with-javascript), which handles
iterators.

**The `searchParams` method won’t give out objects**, if that’s what you want,
but you can make one with `reduce`; [the reduce guide](/reduce) explains the
same accumulator pattern in more detail:

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

const paramObject = params.reduce(
  (acc, [key, val]) => {
    acc[key] = val
    return acc
  },
  {} as { [k: string]: string }
)

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:

```ts
const searchParams = new URLSearchParams({ foo: 'bar', baz: 'fooz' })

console.log(searchParams.toString())
// foo=bar&baz=fooz
```

Nested array works too:

```ts
const searchParams = new URLSearchParams([
  ['foo', 'bar'],
  ['baz', 'fooz'],
])

console.log(searchParams.toString())
// foo=bar&baz=fooz
```

Append params as you go:

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

console.log(searchParams.toString())
// 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.

## Append params to existing URL

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

```ts
const url = new URL('https://example.com')
const params = { foo: 'bar', baz: 'fooz' }

Object.entries(params).forEach(([key, val]) => {
  return url.searchParams.set(key, val)
})

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

## Conclusions

The URL helpers have been widely supported already for a good while now. Before
we needed to use external packages like `qs`, which is about 30kB (it also does
a lot more though, and has its use-case for sure).

Hope this was helpful, thanks for reading!
