Categories
JavaScript

Using the URLSearchParams Object in JavaScript — Part 2

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 this article, we continue from part 1 of this guide.

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'));

There are other ways to create URLSearchParams object which involves passing in other kinds of objects. To see the details see the Part 1 of this guide.

More 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.

get

The get method of the URLSearchParams object let us get a value of the query string by the given key. It takes one argument, which is the string with the key name. It returns the USVString of the value if the search parameter is found, otherwise, it returns null . For example, if we have the following query string and URLSearchParams object like in the code below:

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

Then we get 1 from the console.log statement we have above. If we have more than one key-value pair with the same key like in the following example:

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

Then we get the first value that’s present as the value returned from the get method. If we want to get all the values associated with the given key, we can use the getAll method. It’s the same even if we didn’t use the append method to add more key-value pairs to the query string:

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

In the above example, we still get 1 from the console.log output above.

If we try to get a value with a key that didn’t exist, then we get null returned, like in the example below:

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

We get null from the console.log statement above since we don’t have a search parameter with the key 'abc' .

getAll

With the getAll method, we can get all the values with the associated key name. It takes one argument, which is a string with the key name and returns USVString array with all the values associated with the key name. 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('key1', 2);
params.append('key1', 3);
console.log(params.getAll('key1'));

Then we get [“1”, “2”, “3”] from the console.log statement above.

has

The has method returns a boolean value that is true if the value with the given key exists. It takes one argument, which is a string with the key name that we want to look up. For example, we can use the has 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', 2);
params.append('key1', 3);
console.log(params.has('key1'));
console.log(params.has('abc'));

When we run the code above, we get that the first console.log statement will output true while the second one will output false . This is what we expect since we have ‘key1’ as the key of one or more search parameters, but we don’t have any search parameter with 'abc' as the key.

keys

We can use the keys method to get an iterator which let us iterate through all the search parameter keys in our query string. The keys are all USVString objects. It takes no arguments and returns an iterator which let us iterate through the search parameter keys. For example, we can write:

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

Then we get the following out from the console.log statements above:

key1  
key2

set

The set method of the URLSeacrchParam instance let us set the value with the given search parameter key. It takes 2 arguments. The first is a string with the search parameter key, and the second is the value that you want to set as the value with the given key. If there’re several values with the same key, then they’ll be deleted. If the search parameter with the given key doesn’t exist, then this method will create it.

For example, we can use it like the following code:

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

If we run the code above, will get the array[“5”] from the first console.log statement above. All the other values for key1 are removed as we expected. The second console.log statement will get us key1=5&key2=2 which matches what we have from the getAll method. We can also use it to create a new search parameter key-value pair, like we do with the following code:

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

After we run the code above, we get back [“1”] from the first console.log statement, which means the search parameter with the key 'abc' and the value 1 is created, like we expected. The query string that we get when we use the toString() method is key1=1&key2=2&key1=2&key1=3&abc=1 , which is consistent with what we get from the getAll() method.

sort

We can sort the key-value pairs of a URLSearchParams object by its keys with the sort() method. The sort order is determined by the Unicode code points of the keys. The relative order between key-value pairs with the same keys will be preserved. This method takes no arguments and returns undefined . For instance, we can use it 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', 2);
params.append('key1', 3);
params.set('abc', 1);
params.sort();
console.log(params.toString());

If we run the code above, we get:

abc=1&key1=1&key1=2&key1=3&key2=2

from the console.log statement’s output, which is what we expect since 'abc' has lower code points than 'key1' and ‘key1' has lower code point value than ‘key2' .

toString

As we can see from the earlier examples, the toString() method returns the query string which we can put in a URL. The query string returned will be include the results after manipulation of the URLSearchParams object are done. Note that the returned query string will not have the question mark in front of it, unlike what’s returned from window.location.searh. For example, if we have:

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.set('key5', 5);
console.log(params.toString());

Then we get back:

'key1=1&key2=2&key3=3&key4=4&key5=5'

Which is what we expected. We have all the search parameters we parsed from the URL object and whatever we append with the URLSearchParams object’s append() method and also what we added with the set() method.

values

The values method returns an iterator that let us iterate through all the values contained in the URLSearchParams object. Iterators can be iterated through by the for...of loop and operated on by the spread operator. It takes no arguments. 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.set('key5', 5);
for (const value of params.values()) {
  console.log(value);
}

Then we get the following output from the console.log statements in the loop:

1  
2  
3  
4  
5

Which are the values that we set in the search parameters.

Catches When Using URLSearchParams Object

The URLSearchParams constructor can’t parse full URLs. So something like:

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

will not work. When we run the code above, we get the following outputs from the console.log statements:

https://example.com?key1 1
key2 2

As we can see, the whole URL before the first equal sign was parsed as the key of the first search parameter, which is wrong. This means that we have to use the URL object’s search property to get the query string and pass it in like we do in the example below:

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);
}

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

key1 1  
key2 2

The output above is what we want since these are the actual search parameter key-value pairs.

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. The only catch is that we have to pass in a query string to the constructor, or sequences like Maps and arrays with key-value pairs as an array with key as the first element and the value as the second element. See Part 1 for more details on how to construct URLSearchParams objects.

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.