How to get the URL Parameters in JavaScript

It’s no secret that JavaScript is now all around us, most html forms are using JavaScript for validation and of course there’s now JavaScript on the server. This post covers how to get the query string from the current page’s url.

So, let’s start with the really simple part, how to get the page’s current url.

//get the current page's full URL.
var currentPageUrl = window.location.href

window.location.href get’s the page’s current full url including the query string. This would probably work in almost every case.

For example, let’s say we wanted to know if our form was on the signup page, we could search for the value “signup” in the url and it would give us a good enough idea of whether they are on the page or not.

//check if they are on signup page & then do some operation. Possibly we want to mark this in their cookie or do a callout to our marketing automation software.
if (isOnSignupPage(window.location.href) ) {
	doSomething();
}

function doSomething() {
 // ToDo
}

function isOnSignupPage(theUrl) {
	return theUrl? theUrl.toLowerCase().indexOf('signup') > -1 : false;
}

That would probably work well enough most of the time, but what about when we need a certain query string value?

Here’s a really simple function that works well on any url and can look for basically any field. It’s implemented this way so it can also potentially work on links.

function getQueryStringValue( field, url ) {
    var href = url ? url : window.location.href;
    var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
    var string = reg.exec(href);
    return string ? string[1] : null;
};

Alternatively if you really just need the query string values, you could definitely also look at using window.location.search which returns all of the data at the start of the question mark.

Basically, you would do something like:

function getQueryStringValue( field ) {
    var href = window.location.search;
	
	// check it's not undefined
	if ( !window.location.search) {
		return null;
	}
	
    var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
    var string = reg.exec(href);
    return string ? string[1] : null;
};

In either case, we can simply call the function from our code and carry on.

Author: Brian Cline

Brian is a programmer living in Niagara Falls with ten years of development experience. He is passionate about automation, business process re-engineering, and gamification. For the last six years or so, he has been working with Salesforce and JavaScript.

Related Posts

Sharing is Caring