Question

How to Get Query String Values in JavaScript

javascripturlpluginsquery-string

Question

How can query string values be retrieved in JavaScript, with or without jQuery, without relying on a plugin?

For example, given a URL such as:

https://example.com/products?category=books&page=2

how can JavaScript read values like category and page from the query string?

If a built-in approach exists, how does it work? If not, what alternatives are commonly used?

Short Answer

By the end of this page, you will understand what a query string is, how to read its values in JavaScript, and why modern code usually uses URLSearchParams instead of jQuery plugins or manual string parsing. You will also see examples, common mistakes, and a small practical project.

Concept

A query string is the part of a URL that comes after the ?.

Example:

https://example.com/search?q=javascript&page=3

In this URL:

  • q=javascript
  • page=3

are query parameters.

JavaScript often needs to read these values to:

  • filter search results
  • load a specific page of data
  • track campaign information
  • restore application state from a URL

In modern JavaScript, the standard way to read query string values is with the built-in URLSearchParams API.

Example:

const params = new URLSearchParams(window.location.search);
const query = params.get('q');
console.log(query); // "javascript"

This matters because:

  • it is built into the browser
  • it avoids fragile manual string parsing
  • it correctly handles URL encoding in most common cases
  • it makes code easier to read and maintain

Older codebases sometimes used jQuery helper functions or plugins because jQuery does not include a built-in query-string parser. Today, if you do not need to support very old environments, plain JavaScript is usually the best choice.

Mental Model

Think of a URL like a street address with extra sticky notes attached.

  • The main URL points to the page.
  • The query string is a set of labeled notes such as page=2 or sort=price.
  • URLSearchParams is like a helper that reads those labels for you.

Instead of cutting the address apart by hand, you ask the helper:

  • “What is the value of page?”
  • “Is there a sort parameter?”

That is easier and safer than manually splitting strings yourself.

Take Quiz

Syntax and Examples

The modern syntax is:

const params = new URLSearchParams(window.location.search);
const value = params.get('key');

Example 1: Read a single query parameter

If the current URL is:

https://example.com/search?q=javascript&page=2

then:

const params = new URLSearchParams(window.location.search);

console.log(params.get('q'));    // "javascript"
console.log(params.get('page')); // "2"
console.log(params.get('sort')); // null

Explanation:

  • window.location.search returns the query string, including the leading ?
  • new URLSearchParams(...) parses it
  • .get('name') returns the value for that parameter
  • if the parameter does not exist, .get() returns null

Example 2: Read multiple values with the same key

URL:

https://example.com/products?tag=js&tag=web&tag=frontend

Code:

const params = new URLSearchParams(window.location.search);
const tags = params.getAll('tag');

console.log(tags); // ["js", "web", "frontend"]

Use .getAll() when the same parameter can appear more than once.

Example 3: Check whether a parameter exists

const params = new URLSearchParams(window.location.search);

if (params.has('page')) {
  console.log('Page parameter exists');
}

Older manual approach

Before URLSearchParams, developers often wrote custom parsing code:

function getQueryParam(name) {
  const query = window.location.search.substring(1);
  const pairs = query.split('&');

  for (const pair of pairs) {
    const [key, value] = pair.split('=');
    if (key === name) {
      return decodeURIComponent(value || '');
    }
  }

  return null;
}

console.log(getQueryParam('page'));

This works for simple cases, but built-in APIs are usually better.

Step by Step Execution

Consider this URL:

https://example.com/shop?category=books&page=2

And this code:

const params = new URLSearchParams(window.location.search);
const category = params.get('category');
const page = params.get('page');

console.log(category);
console.log(page);

Step by step:

  1. window.location.search returns:

    "?category=books&page=2"
    
  2. new URLSearchParams(window.location.search) creates an object that understands the query string.

  3. params.get('category') looks for the key category and returns:

    "books"
    
  4. params.get('page') looks for the key page and returns:

    "2"
    
  5. console.log(category) prints:

    books
    
  6. console.log(page) prints:

    2
    

Important detail:

  • Query string values are returned as strings.
  • If you need a number, convert it yourself.

Example:

const pageNumber = Number(params.get('page'));
console.log(pageNumber + 1); // 3

Real World Use Cases

Query string parsing is used in many common situations:

Search pages

/search?q=laptop&sort=price

JavaScript reads q and sort to decide what results to show.

Pagination

/products?page=4

The app reads the page number and loads the correct data.

Filters in dashboards or admin panels

/orders?status=paid&region=eu

The UI can restore selected filters from the URL.

Marketing and analytics

/?utm_source=newsletter&utm_campaign=spring-sale

Scripts may read these values for tracking or customization.

Deep linking in single-page apps

/app?tab=settings

The app can open the right section immediately when the page loads.

Take Quiz

Real Codebase Usage

In real projects, developers usually combine query parameter reading with a few common patterns.

Validation

Never assume a parameter is present or valid.

const params = new URLSearchParams(window.location.search);
const page = Number(params.get('page')) || 1;

Guard clauses

If a required parameter is missing, exit early.

const params = new URLSearchParams(window.location.search);
const token = params.get('token');

if (!token) {
  console.error('Missing token');
} else {
  console.log('Token found:', token);
}

Default values

Provide fallback values when a parameter is absent.

const params = new URLSearchParams(window.location.search);
const sort = params.get('sort') || 'name';

Parsing and sanitizing user input

Query strings come from the URL, so they should be treated as external input.

const params = new URLSearchParams(window.location.search);
const limit = Math.min(Number(params.get('limit')) || 10, 100);

Building reusable helper functions

In larger codebases, teams often wrap this logic in a utility.

function getParam(name, defaultValue = null) {
  const params = new URLSearchParams(window.location.search);
  return params.get(name) ?? defaultValue;
}

This keeps components and pages simpler.

Common Mistakes

1. Expecting a number instead of a string

Broken expectation:

const params = new URLSearchParams(window.location.search);
const page = params.get('page');

console.log(page + 1); // "21" if page is "2"

Why it happens:

  • .get() returns a string

Fix:

const page = Number(params.get('page'));
console.log(page + 1); // 3

2. Forgetting that a missing parameter returns null

Broken code:

const params = new URLSearchParams(window.location.search);
const sort = params.get('sort');

console.log(sort.toUpperCase());

If sort is missing, this crashes.

Fix:

const sort = params.get('sort') || 'name';
console.log(sort.toUpperCase());

3. Parsing the query string manually when not needed

Broken approach:

const query = window.location.search;
const parts = query.split('&');

Problem:

  • this is easy to get wrong
  • it does not clearly handle encoding or repeated keys

Better:

const params = new URLSearchParams(window.location.search);

4. Ignoring repeated parameters

URL:

?tag=js&tag=web

Broken assumption:

params.get('tag'); // only gets the first value

If you need all values:

params.getAll('tag');

5. Assuming jQuery has a built-in method

jQuery does many DOM and event tasks, but it does not provide a standard built-in query-string parser. Beginners sometimes look for something like this:

$.getQueryString('page'); // not a built-in jQuery method

Use JavaScript's built-in URL APIs instead.

Comparisons

ApproachBuilt-inEasy to readHandles repeated keysRecommended today
URLSearchParamsYesYesYes, with getAll()Yes
Manual string parsingYes, but custom codeUsually noOften poorlyOnly for special cases
jQuery pluginNoDepends on pluginDepends on pluginUsually no

URLSearchParams vs manual parsing

  • URLSearchParams is shorter and clearer.
  • Manual parsing gives more control, but adds complexity.
  • Manual parsing is more error-prone for beginners.

JavaScript vs jQuery for query strings

TaskjQueryPlain JavaScript
DOM selectionCommonly used in older codedocument.querySelector()
EventsCommonly used in older codeaddEventListener()
Query string parsingNo standard built-in helperURLSearchParams

For this specific problem, plain JavaScript is the normal choice.

Take Quiz

Cheat Sheet

// Read the current page query string
const params = new URLSearchParams(window.location.search);

// Get one value
params.get('page');

// Get all values for repeated keys
params.getAll('tag');

// Check if a key exists
params.has('sort');

// Convert to number
Number(params.get('page'));

// Fallback value
params.get('sort') || 'name';

Rules to remember

  • window.location.search includes the leading ?
  • params.get('key') returns a string or null
  • use Number(...) if you need a numeric value
  • use getAll(...) for repeated parameters
  • jQuery does not include a standard built-in query-string parser

Common edge cases

  • Missing key → null
  • ?page=2 → "2", not 2
  • ?tag=js&tag=web → use getAll('tag')
  • Empty value like ?q= → returns ""

FAQ

How do I get a query string value in JavaScript?

Use URLSearchParams:

const params = new URLSearchParams(window.location.search);
const value = params.get('key');

Does jQuery have a built-in function for query string parameters?

No. jQuery does not provide a standard built-in method for reading query string values.

What does window.location.search return?

It returns the query-string part of the current URL, including the leading ?.

Why does .get() return a string instead of a number?

Because URL query parameters are text. Convert them with Number() if needed.

How do I handle repeated query parameters?

Use getAll():

params.getAll('tag');

What happens if the parameter does not exist?

params.get('missingKey') returns null.

Should I still use a plugin for this?

Usually no. Modern JavaScript has built-in support through URLSearchParams.

Can I use this outside the browser?

Yes, if your environment supports the URL and URLSearchParams APIs. In browsers, it works naturally with window.location.search.

Take Quiz

Mini Project

Description

Build a small product listing page script that reads filter values from the URL. This demonstrates how query parameters control page behavior in a practical way, such as selecting a category, setting a sort order, and choosing a page number.

Goal

Create a script that reads category, sort, and page from the query string and prints user-friendly output with safe default values.

Requirements

  1. Read category, sort, and page from the current URL.
  2. Use default values if any parameter is missing.
  3. Convert page to a number.
  4. Prevent invalid page values by falling back to 1.
  5. Display the final values in the page and in the console.
Take Quiz

Keep learning

Related questions

View more