If you’ve been a developer for some time you will have undoubtedly worked with URLs before. It’s funny and frustrating at the same time how such a simple thing as URL manipulation can become so messy and prone to errors.
In this article, I want to take a deep dive into the JavaScript URL object. This object takes away most headaches from dealing with URLs and helps us write cleaner and better code.
Creating an URL Object
You create an URL Object with the URL constructor method. You can either pass a full URL to the constructor or pass a path with an optional base URL as the second parameter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can further construct the URL through its public properties.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Note that URLs are encoded according to the rules found in RFC 3986. For example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can use the same properties to retrieve information from a URL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Let’s create a simple method that constructs a URL based on a base URL and an array of query params. We will do this in two ways, first the old-fashioned way and secondly with the URL object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The URL object is a very useful addition that makes dealing with URLs less error-prone and easier at the same time.
Thanks for reading. If you have thoughts on this, be sure to leave a comment!
If you like my content and want to support my efforts, consider becoming a Medium subscriber through my affiliate link. It will cost you nothing extra, but Medium will give parts of the proceeds to me for referring you.
And if you want, you can connect with me on LinkedIn or Twitter!
LEAVE A REPLY
Your email address will not be published. Required fields are marked *
LEAVE A REPLY
Your email address will not be published. Required fields are marked *