W3jar
267 words
1 minutes

How to Get Query String Values From URL In JavaScript

To get query string values from a URL in JavaScript, you can use the URL and URLSearchParams interfaces, which provide a straightforward way to work with query strings. Here’s a step-by-step guide on how to achieve this:

Using URL and URLSearchParams#

  1. Create a URL object: The URL object represents the entire URL and provides convenient methods to work with its components.

  2. Extract query parameters using URLSearchParams: The URLSearchParams object allows you to work with the query string parameters easily.

Here’s a basic example:

// Example URL
const url = "https://example.com/page?name=JohnDoe&age=25";

// Create a URL object
const urlObject = new URL(url);

// Get the query string from the URL
const queryParams = new URLSearchParams(urlObject.search);

// Access individual query parameters
const name = queryParams.get("name"); // 'JohnDoe'
const age = queryParams.get("age"); // '25'

console.log("Name:", name);
console.log("Age:", age);

Using window.location.search#

If you want to get query parameters from the current page URL, you can use window.location.search in combination with URLSearchParams:

// Get the query string from the current page URL
const queryParams = new URLSearchParams(window.location.search);

// Access individual query parameters
const name = queryParams.get("name");
const age = queryParams.get("age");

console.log("Name:", name);
console.log("Age:", age);

Handling Multiple Values#

If a query parameter can have multiple values, you can use getAll:

const queryParams = new URLSearchParams(
    "items=apple&items=banana&items=cherry"
);

const items = queryParams.getAll("items"); // ['apple', 'banana', 'cherry']
console.log("Items:", items);

Iterating Over Query Parameters#

You can also iterate over all query parameters using forEach:

const queryParams = new URLSearchParams("name=JohnDoe&age=25");

queryParams.forEach((value, key) => {
    console.log(`${key}: ${value}`);
});

Summary#

  • URL: Useful for parsing and manipulating the full URL.
  • URLSearchParams: Provides methods to work with query strings, including get, getAll, and forEach.

These methods provide a clean and effective way to handle query string parameters in modern JavaScript.