Categories
JavaScript

Manipulate URLs and Query String with JavaScript

Spread the love

Like any other programming language, JavaScript has many handy tricks that let us write our programs more easily. In this article, we will look at how to manipulate URLs with the URL object with various properties and manipulate query strings with the URLSearchParams object.

Manipulate URLs

With the URL object, we can pass in a URL string and extract and set various parts of a URL and create a new URL. We can create a URL object by using the constructor. The constructor takes up to 2 arguments. We can have one argument being the complete URL string, or we can pass in a relative URL string as the first argument and the hostname as the second argument. For example, we can either write:

new URL('http://medium.com');

or

new URL('/@hohanga', 'http://medium.com');

In the last part, we looked at the hash and host property by looking at the following examples:

const url = new URL('http://example.com/#hash');
console.log(url.hash);
url.hash = 'newHash';
console.log(url.toString());

If we run the code, we can see that the first console.log statement logs '#hash'. Then we assigned the value 'newHash' to the url’s hash property. Then when we run the toString() method on the url object and the run the console.log method on the value returned by toString(), we get '[http://example.com/#newHash](http://example.com/#newHash)' which is the new value of the URL with the new hash.

const url = new URL('http://example.com/#hash');
console.log(url.host);
url.host = 'newExample.com';
console.log(url.toString());

When we run the code, we can see that the first console.log statement logs '#hash'. Then we assigned the value 'example.com' to the url’s hash property. When we run the toString() method on the url object and use the console.log method on the value returned by toString() , we get ‘[http://newexample.com/#hash](http://newexample.com/#hash)’ which is the new value of the URL with the new hash.

In this part of the series, we will look at the other parts of the URL object. To get and set the whole URL we can use the href property. For example, we can write the following code:

const url = new URL('http://example.com/href1/href2');
console.log(url.href);
url.href = 'http://example.com/newHref1/newHref2';
console.log(url.toString());

In the code above, the first console.log statement would get us the whole URL, that is, ‘[http://example.com/href1/href2'](http://example.com/href1/href2%27) . Then once we set a new value to the href property as we did on the third line, then we should get a string with a new URL when we run the console.log statement at the bottom. Therefore, we should get ‘[http://example.com/newHref1/newHref2](http://example.com/newHref1/newHref2)’ from the console.log statement on the last line.

We can use the username and password properties to set the username and password portion of the URL. The username is the part of the URL that’s right after the protocol and before the colon. The password portion of the URL is between the colon and the ampersand sign. For example, https://username:password@example.com. To get and set the username portion of the URL, we can use the username property. For example, we can write:

const url = new URL('https://username:password@example.com');
console.log(url.username);
url.username = 'newUsername';
console.log(url.toString());

The first console.log should output 'username' which is the username of the original URL. Then we set the username property to 'newUsername' so that when returning the URL object converted to a string, we get that we have ‘[https://newUsername:password@example.com/](https://newUsername:password@example.com/)’ .

Likewise, we can do the same thing with the password property. For example, we can write:

const url = new URL('https://username:password@example.com');
console.log(url.password);
url.password = 'newPassword';
console.log(url.toString());

The first console.log should output 'password' which is the username of the original URL. Then we set the password property to 'newPassword' so that when returning the URL object converted to a string, we get that we have ‘[https://newUsername:password@example.com/](https://username:newPassword@example.com/)’ .

With the pathname the property, we can set the part of the URL after the host part — that is, the relative URL after the first slash. For instance, we can write the following code:

const url = new URL('https://example.com/path1/path2');
console.log(url.pathname);
url.pathname = '/newPath1/newPath2';
console.log(url.toString());

The first console.log should output '/path1/path2' , which is the username of the original URL. Then we set the pathname property to '/newPath1/newPath2' so that when returning the URL object converted to a string, we get that we have ‘[https://newUsername:password@example.com/](https://example.com/newPath1/newPath2)’ .

There’s also the port and protocol properties to manipulate the port portion and the protocol portion of the URL respectively. If we have a URL like https://example.com:8888 then 8888 would be the port number. For HTTP the default it 80 and for HTTPS the default port is 443, so if it’s not specified then the default port is used. We can get and set them like all the other properties mentioned above. For example, we can write:

const url = new URL('https://example.com:8888');
console.log(url.port);
url.port = '3333';
console.log(url.toString());

console.log(url.protocol);
url.protocol = 'http';
console.log(url.toString());

Then we should get something like:

8888
https://example.com:3333/
https:
http://example.com:3333/

from the 4 console.log statements.

Manipulate Query Strings

With the URLSearchParams object, we can get the query string from a URL string. For example, if we have had the URL https://example.com/?key1=value1&key2=value2 then we can use the URL’s search property to get the query string from the URL as we do with the following code:

const url = new URL('[https://example.com/?key1=value1&key2=value2'](https://example.com/?key1=value1&key2=value2%27));
console.log(url.search);

Then we get back ?key1=value1&key2=value2 from the console.log output. Note that the search property only gets the whole query string. There’s nothing in the URL object that lets us manipulate the query string. This is where the URLSearchParams object comes in. We can get it from the URL object by using its searchParams property. For example, if we have the same URL as the earlier example, then we can write:

const url = new URL('https://example.com/?key1=value1&key2=value2');
console.log(url.`searchParams`);

With the URLSearchParams object, we can use its methods to get and set various parts of the query string. We can use the get method to get the value of a search parameter given a key for it. For instance, we can write:

const url = new URL('https://example.com/?key1=value1&key2=value2');
console.log(url.searchParams.get('key1'));
console.log(url.searchParams.get('key2'));

Then we get back the following:

value1
value2

These are the values of the search parameters that we expect. There’s also a getAll method to get the values of all search parameters with the given key. If we write the following code:

const url = new URL('https://example.com/?key1=value1&key1=value2&key2=value3');
console.log(url.searchParams.getAll('key1'));

So if we have the URL with the query string above, which has 2 values set for the key1 search parameter, then when we call url.searchParams.getAll(‘key1’) we get back [“value1”, “value2”] .

There’s also a keys method to get all the keys from the query string. Again, if we have URL the example above, we can get all the keys from the query string with the key method like we do below:

const url = new URL('[ttps://example.com/?key1=value1&key1=value2&key2=value3');
console.log([...url.searchParams.keys()]);

The keys method returns an iterator object, so if we want to get an array, we have to use the spread operator as we did above. Once we did that, we get back [“key1”, “key1”, “key2”] .

To check if a key exists in the search parameters of our query string, we can use the has method. It’s very straightforward to use, we just have to pass in the string with the key name we want to look for:

const url = new URL('https://example.com/?key1=value1&key1=value2&key2=value3');
console.log(url.searchParams.has('key1'));
console.log(url.searchParams.has('key4'));

If we run the code above, we should get:

true
false

The key method returns a boolean true if the value for the given key exists and false otherwise. To add a search parameter to the query string, we can use the append method. We can append as many search parameters with the same keys as many times as we like. For example, we can call the append method like in the following code:

const url = new URL('https://example.com/?key1=value1&key1=value2&key2=value3');
url.searchParams.append('key4', 'value4');
url.searchParams.append('key4', 'value5');
url.searchParams.append('key5', 'value5');
console.log(url.toString());

Then the console.log at the end should output https://example.com/?key1=value1&key1=value2&key2=value3&key4=value4&key4=value5&key5=value5.

To edit a key that’s in a URL, we can use the URLSearchParamsset method. It takes in the string of the key of the search parameter as the first argument the string of the value you want to set for the search parameter as the second argument. For example, we call it like in the following code:

const url = new URL('https://example.com/?key1=value1&key1=value2&key2=value3');
url.searchParams.set('key1', 'newValue');
console.log(url.toString());

Then we get back https://example.com/?key1=newValue&key2=value3. The set method will remove duplicate search parameters with the same keys when it runs and set the new value to the one that’s left. So the second instance of the key1 search parameter is removed and newValue is set as the value of the first instance of the key1 search parameter.

Finally, to remove a search parameter with the given key string, we can call the delete method. For example, we can use it as in the following code:

const url = new URL('https://example.com/?key1=value1&key1=value2&key2=value3');
url.searchParams.delete('key1');
console.log(url.toString());

Then we get back https://example.com/?key2=value3. Note that it removes all search parameters with the given key.

Conclusion

JavaScript, like any other programming language, has many handy tricks that let us write our programs more easily. In this article, we looked at how to manipulate URLs with the URL object with various properties and manipulate query strings with the URLSearchParams object. With these tricks, we reduce the effort we put into writing our code making our lives easier.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *