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=javascriptpage=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
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=2orsort=price. URLSearchParamsis 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
sortparameter?”
That is easier and safer than manually splitting strings yourself.
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:
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:
-
window.location.searchreturns:"?category=books&page=2" -
new URLSearchParams(window.location.search)creates an object that understands the query string. -
params.get('category')looks for the keycategoryand returns:
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®ion=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.
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.
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..);
sort = params.();
.(sort.());
Comparisons
| Approach | Built-in | Easy to read | Handles repeated keys | Recommended today |
|---|---|---|---|---|
URLSearchParams | Yes | Yes | Yes, with getAll() | Yes |
| Manual string parsing | Yes, but custom code | Usually no | Often poorly | Only for special cases |
| jQuery plugin | No | Depends on plugin | Depends on plugin | Usually no |
URLSearchParams vs manual parsing
URLSearchParamsis shorter and clearer.- Manual parsing gives more control, but adds complexity.
- Manual parsing is more error-prone for beginners.
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.searchincludes the leading?params.get('key')returns a string ornull- 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
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?
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
- Read
category,sort, andpagefrom the current URL. - Use default values if any parameter is missing.
- Convert
pageto a number. - Prevent invalid page values by falling back to
1. - Display the final values in the page and in the console.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.