JavaScript - Getting query string values

JavaScript - Getting query string values

API, Javascript

One of the key ingredients to an AJAX driven website is the ability to reliably get query string parameters. We will run through an example using the new URLSearchParams API and also a Javascript only implementation for legacy browsers.

Using the URLSearchParams Web API

Consider the url

Get the query string params

var queryParams = new URLSearchParams(;

Iterate & Log

for (var q of queryParams) {

Getters & Setters

queryParams.has("firstName"); // true
queryParams.has("lastName");  // false
queryParams.get("firstName")  // "Bob"
queryParams.getAll("hobby");  // ["Basketball", "Baseball"]
queryParams.append("job", "webdev"); 
queryParams.toString(); // ?id=1&firstName=Bob&hobby=Baseball&hobby=Basketball&job=webdev
queryParams.toString(); // ?id=1&firstName=Bob&hobby=Baseball&hobby=Basketball

Using good ol' Javacsript

Consider the same url:

Get the query string & split

var query =;
var queryParams = query.split("&");

Getting a query string parameter

function getQueryParam(param)
var query =;
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if(pair[0] == param) {
return pair[1];

getQueryParam("firstName"); // "Bob"
getQueryParam("lastName"); // false

Back to The Programmer Blog