Getting Started with the JavaScript URL Object
Learn How To Properly Handle URLs in JavaScript
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.
You can further construct the URL through its public properties.
Note that URLs are encoded according to the rules found in RFC 3986. For example:
Reading Information From The URL
You can use the same properties to retrieve information from a URL.
Use Case
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.
Aside from the second function being much more readable, there are several benefits to the second approach.
- We do not have to think about the
‘?’
and‘&’
characters. - We do not have to manually build the string.
- The params are encoded automatically, is someone injects a param with a space or special character the code does not break.
Additional Resources
Conclusion
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 *