How do you get query string values in JavaScript?

JavaScript

The short answer

Use the URLSearchParams API. It parses the query string and provides methods to get, set, and iterate over parameters. It is built into the browser and works with any URL.

Using URLSearchParams

// URL: https://example.com?search=react&page=2&sort=newest
const params = new URLSearchParams(window.location.search);
params.get('search'); // "react"
params.get('page'); // "2"
params.get('sort'); // "newest"
params.get('missing'); // null

Other useful methods

const params = new URLSearchParams(
'?name=John&age=30&hobby=coding&hobby=reading'
);
params.has('name'); // true
params.getAll('hobby'); // ["coding", "reading"]
params.toString(); // "name=John&age=30&hobby=coding&hobby=reading"
// Iterate over all parameters
for (const [key, value] of params) {
console.log(`${key}: ${value}`);
}

Building query strings

const params = new URLSearchParams();
params.set('search', 'react hooks');
params.set('page', '1');
console.log(params.toString()); // "search=react+hooks&page=1"
// Use with fetch
fetch(`/api/products?${params.toString()}`);

Using the URL API

For parsing full URLs (not just the current page):

const url = new URL(
'https://example.com/search?q=react&page=2'
);
url.searchParams.get('q'); // "react"
url.pathname; // "/search"
url.hostname; // "example.com"

Interview Tip

Show new URLSearchParams(window.location.search) and .get(). That is the modern answer. If the interviewer asks about the old way, the manual approach was splitting the string with split('&') and split('='), but URLSearchParams replaced all of that.

Why interviewers ask this

This tests basic web API knowledge. Query strings are used everywhere — search pages, filters, pagination. Knowing URLSearchParams shows you use modern browser APIs instead of manual string parsing.