DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Reading URL Parameters in JavaScript

Consider the following URL:

https://example.com?shape=circle&color=red
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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`);
Enter fullscreen mode Exit fullscreen mode

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`);
}
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)