Get URL Parameters with JavaScript — Simple URLSearchParams Example

Introduction

Get URL Parameters with JavaScript is a common need when you’re building dynamic web pages. Whether you want to track campaign data, load content, or redirect users, reading query strings is crucial. Here’s a modern way to do it.

How to Get URL Parameters with JavaScript

Use the built-in URLSearchParams API to grab values directly from the current page’s URL:


const params = new URLSearchParams(window.location.search);
const userId = params.get(‘user’);
console.log(userId); // e.g., from ?user=42

How This Works

The Get URL Parameters with JavaScript example uses URLSearchParams, which parses the query string portion of the URL. You can then use .get() to retrieve specific values.

Why Use This?

Get URL Parameters with JavaScript lets you react to dynamic input in the URL, useful for filtering, authentication, analytics, and more.

Common Mistake

Forgetting to check if a parameter exists before using it can lead to null errors.

Pro Tip

Use params.has('user') to check if a key exists before accessing it.

Related Snippet

Toggle Dark Mode with JavaScript

1 thought on “Get URL Parameters with JavaScript — Simple URLSearchParams Example”

Leave a Comment