Categories
JavaScript

Using the URLSearchParams Object in JavaScript — Part 1

Spread the love

Working with query strings can be a pain if we have to write the code from scratch to parse and modify it. Fortunately, most recent browsers have the URLSearchParams object that can let us deal with query strings easily. With it, is makes it easy to parse and manipulate query strings. We no longer need a third party library or write code from scratch to deal with query strings anymore. In the part 1 of this guide, we will look at how to create URLSearchParams objects and look at a few handy methods which let us get and set key-value pairs of a query string.

Create URLSearchParam Objects

We can create a URLSearchParams object with the URLSearchParams constructor. The URLSearchParams constructor takes one optional argument, which is a USVString argument that has the query string. USVString objects correspond to the set of all possible sequences of Unicode scalar values. In our code, we can treat them the same as regular strings. It can be a sequence of USVStrings or a record that contains USVStrings. In our code, we don’t have to concerned with USVStrings. For all practical purposes, they’re treated as like strings. We can construct a URLSearchParams object like the following code:

const url = new URL('https://example.com?key1=1&key2=2');
const params = new URLSearchParams(url.search);
console.log(params.get('key1'));
console.log(params.get('key2'));

With the code above, we create a URL object, then we get the query string with the search property of the URL object, then we pass that into the URLSearchParams constructor. Then we can use the URLSearchParams object to get the value of the key using the get method of the URLSearchParams object. The console.log statements above should get us the values 1 and 2 respectively.

We can also constructor a URLSearchParams object using an array with entries that are arrays with the key as the first element and the value as the second element. For example, we can construct a URLSearchParams objects with arrays like in the following code:

const params = new URLSearchParams([
  ["key1", 1],
  ["key2", 2]
]);
console.log(params.get('key1'));
console.log(params.get('key2'));
console.log(params.toString());

With the code above, we pass in an array with the key and value in the entries. With the toString() instance method, we can get the full query string easily. The console.log statements above should get us the values 1 and 2 respectively with the first 2 statements and the last one should get us key1=1&key2=2 . Creating query strings have never been easier with this object.

A third way to construct a URLSearchParams object is with a plain JavaScript object passed into the constructor. The keys would be in the keys of the object, and the values are in the values of the object. For example, we can construct a URLSearchParams object like in the following code:

const params = new URLSearchParams({key1: 1, key2: 2});
console.log(params.get('key1'));
console.log(params.get('key2'));
console.log(params.toString());

The console.log statements above should get us the values 1 and 2 respectively with the first 2 statements and the last one should get us key1=1&key2=2 . Creating query strings have never been easier with this object.

We can also pass in Maps into the constructor and get back a query string. With Maps, we can pass it in like in the following code:

const params = new URLSearchParams(new Map([['key1', 1], ['key2', 2]]));
console.log(params.get('key1'));
console.log(params.get('key2'));
console.log(params.toString());

We should get the same output as the earlier examples with the console.log statements above.

After constructing a URLSearchParams object, we can iterate through it since it’s an array like object. An array like object are objects that have an iterator method included. The method is identified with the Symbol.iterator Symbol. We can iterate through the entries of an array like objects with the for...of loop. For example, if we have the following URLSearchParams object:

const url = new URL('https://example.com?key1=1&key2=2');
const params = new URLSearchParams(url.search);
for (const [key, value] of params) {
  console.log(key, value);
}

Then we get back the following console.log outputs:

key1 1  
key2 2

As we can see, we get back all the query string keys and values with with for...of loop. This is another reason to use the URLSearchParams object to parse query strings. It is an iterable object that lets us get the keys and values easily. This feature is even more useful is we have a long list of query string key-value pairs. Alternatively, we can use the entries method, which is an instance method of an URLSearchParams object. to get back the key-value pairs of a query string, like we do in the following code:

const url = new URL('https://example.com?key1=1&key2=2');
const params = new URLSearchParams(url.search);
for (const [key, value] of params.entries()) {
  console.log(key, value);
}

We should get back the same output as the first example with where we loop through the params object directly with the for...of loop.

Methods

Each URLSearchParams instance has multiple methods available to it to get the keys and values and to manipulate them by adding, changing and removing keys or values. With these methods, we can construct query strings easily without having to do string manipulating directly. If we want to get back the full query string after manipulating, we can get it with the toString() method.

append

The append method lets us add an key-value pair to the URLSearchParams object as a new search parameter. The method takes 2 arguments. One for the key name and one for the value. Both arguments will be converted to strings when we pass them in. We can append the same key multiple times with or without the same corresponding value. For example, we can use the append method like in the following code:

const url = new URL('https://example.com?key1=1&key2=2');
const params = new URLSearchParams(url.search);
params.append('key1', 1);
params.append('key1', 2);
console.log(params.toString());

With the code above, we should get back key1=1&key2=2&key1=1&key1=2 from the console.log statement we have in the code above. As we can see, we can append the same key-value pair as many times as we want and the append method will not attempt to merge them together.

delete

The delete method of the URLSearchParams object will let us delete the key-value pair with the given key. If there’s more than one with the same key, then they’ll all be deleted. If takes one argument, which is the key name as a string. For example, we can write the following code:

const url = new URL('https://example.com?key1=1&key2=2');
const params = new URLSearchParams(url.search);
params.append('key1', 1);
params.append('key1', 2);
params.delete('key1');
console.log(params.toString());

If we run console.log above like we did on the last of the code above, we get back key2=2 . This means that all the key-value pairs with key name key1 were removed from the URLSearchParams object and the corresponding query string.

entries

The entries method gets the key-value pairs from the URLSearchParams object. It takes no arguments and returns an iterator that let us iterate through the key-value pairs. The key-value pairs will be in the form of an array with the key as the first element and the corresponding value as the second element. For example, we can use the entries method like in the following code:

const url = new URL('https://example.com?key1=1&key2=2');
const params = new URLSearchParams(url.search);
for (const [key, value] of params.entries()) {
  console.log(key, value);
}

In the code above, we used the destructuring assignment syntax to decompose the key-value array into their own variables. This is a great way to access the keys and values since we don’t have to use the indexes or assign them to variables with our own code.

forEach

The forEach method let us iterate the values directly without using the entries method. It takes a callback function where can can access the key and value of each URLSearchParams entry. The callback function has the value as the first parameter and the key as the second parameter. For example, if we have the following code:

const url = new URL('https://example.com?key1=1&key2=2');
const params = new URLSearchParams(url.search);
params.append('key3', 3);
params.append('key4', 4);
params.append('key5', 5);
params.forEach((value, key) => {
  console.log(key, value);
})

When we run the code above, we should get the following output from the console.log statements:

key1 1  
key2 2  
key3 3  
key4 4  
key5 5

It’s important to note the value parameter comes before the key, so we don’t reverse them like in most other places.

There are more methods in the URLSearchParams object, we will continue the list of methods and look at the caveats for using the URLSearchParams objects in part 2 of this guide.

Most recent browsers have the URLSearchParams object that can let us deal with query strings easily. Now working with query strings is no longer a pain since we don’t have to write the code from scratch to parse and modify it. With URLSearchParams objects, is makes it easy to parse and manipulate query strings. We no longer need a third party library or write code from scratch to deal with query strings anymore. There are more methods in the URLSearchParams object and some caveats when using it, so stay tuned for Part 2.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.