To get a URL parameter in browser JavaScript, pass window.location.search to URLSearchParams, then call .get() with the parameter name:
// On https://example.com/products?color=blue
const params = new URLSearchParams(window.location.search);
const color = params.get("color");
console.log(color); // "blue"
Replace color with the key you need. If that key isn't present, .get() returns null. No library or regular expression is required.
This reads the current page's query string, the part starting with ? and ending before any # fragment. The examples below use illustrative URLs and console output, so you can test parsing without changing page content. Run each block separately.

Handle missing, empty, and repeated parameters
An absent parameter isn't the same as a parameter with an empty value. That distinction matters for filters, optional fields, and links where the presence of a flag means something even without text after it.
Use .has() to check presence, .get() for the first value, and .getAll() when a key can appear more than once:
const filters = new URLSearchParams(
"tag=boots&tag=trail&coupon=&preview"
);
console.log(filters.get("tag")); // "boots"
console.log(filters.getAll("tag")); // ["boots", "trail"]
console.log(filters.get("missing")); // null
console.log(filters.getAll("missing")); // []
console.log(filters.get("coupon")); // ""
console.log(filters.get("preview")); // ""
console.log(filters.has("coupon")); // true
console.log(filters.has("missing")); // false
As MDN's URLSearchParams reference explains, both ?preview and ?preview= produce an empty string. Parsing doesn't preserve a distinction between those two forms.
Choose your fallback deliberately. filters.get("coupon") ?? "NONE" uses "NONE" only when the key is missing. Using || "NONE" also replaces an empty string. Neither rule is universally right; it depends on what an empty value means in your application.
For repeated keys, don't quietly assume the last value wins. .get() returns the first. Keep .getAll() for multi-select filters, and reject duplicates where your application expects exactly one value. Converting everything with Object.fromEntries() loses repeated entries.
Parameter names are case-sensitive, too: color and Color are different keys.
Read a full URL or a link passed between pages
Sometimes you're checking a campaign link rather than the page currently open. SparkTraffic, a website traffic platform, provides a free UTM builder for creating tagged links; JavaScript lets you inspect the values in those links before using them in your own code.
For a complete URL string, use new URL() and its .searchParams property:
const campaignUrl = new URL(
"https://example.com/offers?utm_source=newsletter&color=blue#sizes"
);
console.log(campaignUrl.searchParams.get("utm_source")); // "newsletter"
console.log(campaignUrl.searchParams.get("color")); // "blue"
Don't pass that entire address directly to new URLSearchParams(). It parses query-string syntax, not full URLs, so it won't recognize the first parameter as you expect.
A relative link needs a base URL. This self-contained example works regardless of which page you're testing on:
const relativeUrl = new URL(
"/offers?coupon=TRAIL",
"https://example.com"
);
console.log(relativeUrl.searchParams.get("coupon")); // "TRAIL"
The URL constructor documentation covers relative references and invalid inputs, which can throw a TypeError.
When passing a value between pages, include it in the destination URL, then use the opening snippet on the receiving page. A local JavaScript variable won't survive a full page navigation by itself. For a non-sensitive preference such as a selected color, a query parameter makes that state shareable and bookmarkable.
Let the parser handle URL encoding
Spaces and punctuation can look different in a URL from the text you receive. URLSearchParams decodes percent-encoded values and treats a literal + in a query string as a space:
const encoded = new URLSearchParams(
"q=trail+shoes&language=C%2B%2B&offer=save%2020%25"
);
console.log(encoded.get("q")); // "trail shoes"
console.log(encoded.get("language")); // "C++"
console.log(encoded.get("offer")); // "save 20%"
Both + and %20 represent a space here. An actual plus sign must arrive as %2B.
Don't call decodeURIComponent() again on the result of .get(). It's already decoded. A second pass can change intentionally encoded text or throw an error on a literal percent sign.
When creating a link, pass raw text to .set() rather than joining strings or pre-encoding the value:
const destination = new URL("https://example.com/next");
destination.searchParams.set("note", "Take a break & enjoy");
console.log(destination.href);
// "https://example.com/next?note=Take+a+break+%26+enjoy"
The ampersand stays inside the value as %26; it doesn't accidentally introduce another parameter. Reading note on the receiving page returns the original text.
Keep fragments separate from query parameters
A question mark after # doesn't start the page's query string. It belongs to the fragment, even if the text looks like a parameter.
const fragmentUrl = new URL(
"https://example.com/products?color=blue#details?size=large"
);
console.log(fragmentUrl.search); // "?color=blue"
console.log(fragmentUrl.hash); // "#details?size=large"
console.log(fragmentUrl.searchParams.get("size")); // null
If size should be a query parameter, use https://example.com/products?color=blue&size=large#details instead. MDN documents .search as the query component, separate from the fragment.
Some single-page applications deliberately put routing information after #, such as #/products?size=large. In that setup, use the router's parameter API or explicitly parse its documented fragment format. Don't merge fragment values into the normal query string by default.
Check whether you need the page URL or the script URL
A parameter on widget.js?theme=dark belongs to the JavaScript file's URL. window.location.search still reads the page address, so it won't find that value unless the page itself also has it.
If you already have the script's complete URL, parse it with new URL(scriptUrl).searchParams. For a classic external script, you can capture document.currentScript.src while the script is initially executing. It isn't a reliable lookup inside a later callback.
MDN's currentScript documentation also distinguishes JavaScript modules, which use import.meta.url instead. Choosing the correct URL comes before choosing a parsing method.
Validate values before displaying or sending them
Parsing gives you strings, not trusted instructions. ?enabled=false produces the string "false", which is truthy in JavaScript. Compare it explicitly with the value your application accepts rather than treating any nonempty string as a boolean.
For a setting such as theme, accept known values like light and dark and fall back for anything else. If you display parsed text, use textContent or a form field's value, not innerHTML. Decoding a URL value does not make it safe HTML.
Keep passwords, access tokens, and personal contact details out of these examples and out of shareable query strings. They can end up in browser history, logs, and analytics. Google's guidance on avoiding personally identifiable information specifically requires page URLs and parameters sent to Analytics to be free of PII.
Read a query value in Google Tag Manager without custom code
If your only goal is to read a parameter in Google Tag Manager, a URL variable can save you a custom script. Create a user-defined variable, select the URL type, choose the Query component, and enter the parameter name as the Query Key.
Google's web variable documentation confirms that URL variables read the current page by default and can use another URL source. Check the result in Preview before connecting it to a tag. Extracting a value makes it available to your setup; it doesn't automatically send that value to Analytics. If a correctly tagged visit still shows up as Unassigned in GA4, check the source and medium against the channel rules before changing the parser.
.webp)
