What is URLSearchParams?
URLSearchParams is a built-in JavaScript interface that makes it easy to work with the query string of a URL.
A query string is the part of a URL that comes after the “?” and contains key-value pairs.
Example URL:
https://example.com/page?customerId=123&status=active
Query string:
customerId=123&status=active
Why Use URLSearchParams?
It helps you:
- Read values from the URL
- Get specific query parameters (e.g., customerId)
- Add, update, or delete query parameters
- Convert query parameters back to a string
It replaces the old manual method of splitting URL strings.
How to Read Query Parameters
Step 1: Get the search/query part
const urlParams = new URLSearchParams(window.location.search);
window.location.search returns:
?customerId=123&status=active
Step 2: Get a value
const cusId = urlParams.get('customerId');
console.log(cusId); // Output: 123
Another example:
const status = urlParams.get('status');
console.log(status); // Output: active
Check if a parameter exists
if (urlParams.has('customerId')) {
console.log("Customer ID is available");
}
Loop through all query parameters
for (const [key, value] of urlParams) {
console.log(key, value);
}
Add or Update a Parameter
urlParams.set('page', 2);
console.log(urlParams.toString());
// customerId=123&status=active&page=2
Delete a Parameter
urlParams.delete('status');
console.log(urlParams.toString());
// customerId=123
Create a New URL with Modified Parameters
const newUrl = window.location.pathname + '?' + urlParams.toString(); console.log(newUrl);
Use Case: Passing Customer ID From Suitelet to HTML
Suitelet passes a URL like:
https://.../page.html?customerId=5678
Your HTML/JS retrieves it:
const urlParams = new URLSearchParams(window.location.search);
const cusId = urlParams.get('customerId');
console.log('Customer ID:', cusId);
Summary
URLSearchParams is the simplest and cleanest way to handle URL parameters in JavaScript. It helps you read, modify, and manage query strings without manually parsing them.