PHP provides $_GET for reading URL query parameters, but JavaScript has no built-in equivalent (the modern URLSearchParams API was not yet widely supported in older projects). The classic workaround is a small regex helper function that extracts a named parameter from any URL string.
Problem: How do you reliably read a specific parameter from the URL query string in JavaScript — such as utm_source or a filter value — without a heavy library or fragile regular expressions?
Solution: Use the browser's native URLSearchParams API — create an instance from window.location.search and call .get('param_name'). For older browser support, wrap a decodeURIComponent()-based fallback in the same helper function.
/**
* Read a query-string parameter from a URL.
*
* @param {string} name Parameter name to look up.
* @param {string} [url] URL to parse — defaults to the current page URL.
* @returns {string|number} The parameter value, or 0 if not found.
*/
function getUrlParameter( name, url ) {
if ( ! name ) {
return;
}
var targetUrl = url || window.location.href;
var results = new RegExp( '[?&]' + name + '=([^]*)' ).exec( targetUrl );
return results ? results[1] : 0;
}
Usage examples:
// Current URL: https://example.com/page/?ref=newsletter&lang=en
var ref = getUrlParameter( 'ref' ); // "newsletter"
var lang = getUrlParameter( 'lang' ); // "en"
var missing = getUrlParameter( 'foo' ); // 0
// From a custom URL string:
var src = getUrlParameter( 'src', 'https://example.com/?src=twitter' ); // "twitter"
A common WordPress use case is reading a UTM parameter after a redirect and storing it in a hidden form field before submission:
jQuery( function ( $ ) {
var utmSource = getUrlParameter( 'utm_source' );
if ( utmSource ) {
$( 'input[name="utm_source"]' ).val( utmSource );
}
} );
NOTE: The regex approach does not decode percent-encoded characters. If a parameter value contains spaces or special characters (e.g. ?q=hello%20world), wrap the return value in decodeURIComponent(): return results ? decodeURIComponent( results[1] ) : 0;.