JavaScript / ECMAScript

URL Query String in JS

Extract the query string portion of a URL (everything between `?` and `#` or end-of-string).

Try it in the JS tester →

Pattern

regexJS
\?([^#\s]+)   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("\\?([^#\\s]+)", "g");
const input = "https://example.com/page?utm_source=google&id=42";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

\? matches the literal question mark. ([^#\s]+) captures everything up to (but not including) a `#` (fragment) or whitespace (URL boundary). Use URL parsing libraries for production, but this regex is handy for quick log scraping.

Examples

Input

https://example.com/page?utm_source=google&id=42

Matches

  • ?utm_source=google&id=42

Input

/api?token=abc#section

Matches

  • ?token=abc

Input

no query string here

No match

Same pattern, other engines

← Back to URL Query String overview (all engines)