Reading URL Parameters in JavaScript
Consider the following URL:
example.com?shape=circle&color=red
What if we wanted to extrapolate shape
, color
, and any other query parameters from that URL using JavaScript?
Well, one approach would be by using the very handy URLSearchParams
object:
const url = window.location.href; // The URL of the current page
const params = new URLSearchParams(url);
Once you've constructed an instance of URLSearchParams
with a valid URL, you can start working with the URL's parameters:
const shape = params.get(`shape`);
const color = params.get(`color`);
However, it's important to first check whether the URL parameter that you're trying to read even exists in the first place:
if (params.has(`shape`)) {
const shape = params.get(`shape`);
}
Conclusion
That's about it!
Working with URLs in JavaScript doesn't necessarily require writing tedious regular expressions or parsers. Instead, it can be a very simple and readable process.