Get and Set Query String Variables with JavaScript

Query strings are a handy way to pass information. With them and a little JavaScript, you can transform a “static” page into one with infinite varieties.

Here’s a straight JavaScript function (no jQuery needed) that will return the value of any parameter in the query string:

function getqsv(param) {
	var qs = window.location.search.substring(1);
	var v = qs.split('&');
	for (var i=0;i<v.length;i++) {
		var p = v[i].split('=');
		if (p['0'] == param) { return p['1']; }
	}
	return null;
}

It grabs the full query string, explodes it into chunks separated by ampersands, then loops through each chunk to see if the parameter name matches the one that you’re looking for. If it gets through the whole loop without a match, it returns null.

Note: This function is pretty basic and so an ampersand in one of your values will cause problems.

Let’s try it out: Add ?test=something to the end of this page’s URL, then reload the page. Of course, “something” can be whatever you’d like it to be.

That example is using this code:

var test_qs_value = getqsv('test');

It’s sometimes useful to go the other way too. Here’s a JavaScript function to change the query string without reloading the page. (Again, this is pure JavaScript, no jQuery needed.) Be sure to change the url variable to your page’s URL!

function updateqs(param,value) {
	var url = '/code/get-query-strings-with-javascript';
	var new_url = url + '?' + param + '=' + value;
	history.pushState(null, null, new_url);
}

Here’s an example. Start typing in the box below and you’ll see the query string in your browser’s URL bar start updating automatically.

Note: The pushState functionality is limited to newer browsers so you’ll want a fallback if it‘s critical that all users be able to use this.


Comments

Loading…

This post was published on April 9th, 2017 by Robert James Reese in JavaScript. Before using any of the code or other content in this post, you must read and agree to our terms of use.