Sign in
Log inSign up

Reading URL Parameters in JavaScript

Nathan's photo
Nathan
·Sep 17, 2021·

1 min read

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.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct