How to get a value from the URL GET parameters in JavaScript
Very often we need values from the URL query string. PHP has $_GET for this, but jQuery has no such function. Below are two ways: the browser API and a small helper function I found online.
Problem: How to get the value of a GET parameter from the URL with JavaScript or jQuery?
Solution: Modern browsers have URLSearchParams. For old browsers (Internet Explorer) use a regex helper.
Way 1. URLSearchParams
// URL: https://example.com/page/?ref=newsletter&lang=en var params = new URLSearchParams( window.location.search ); params.get( 'ref' ); // "newsletter" params.get( 'lang' ); // "en" params.get( 'foo' ); // null params.has( 'ref' ); // true
get() also decodes the value: ?q=hello%20world returns "hello world". It works in all current browsers except Internet Explorer.
Way 2. A helper function
If you still have to support Internet Explorer:
// Get a parameter from the URL (the current page URL by default)
function getUrlParameter( name, url ) {
if ( ! name ) {
return;
}
url = url || window.location.href;
var results = new RegExp( '[?&]' + name + '=([^&#]*)' ).exec( url );
return results ? decodeURIComponent( results[1].replace( /\+/g, ' ' ) ) : null;
}
getUrlParameter( 'ref' ); // "newsletter"
getUrlParameter( 'src', 'https://example.com/?src=twitter' ); // "twitter"
For example, put the utm_source of the visit into a hidden form field:
jQuery( function ( $ ) {
var utmSource = getUrlParameter( 'utm_source' );
if ( utmSource ) {
$( 'input[name="utm_source"]' ).val( utmSource );
}
} );
NOTE: The parameter name goes into a regular expression as is. Names with special characters (for example filter[color]) have to be escaped first, or use URLSearchParams.
Sources: