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

http://www.systemoutofmemory.com?id=1&firstName=Bob&hobby=Baseball&hobby=Basketball

Get the query string params

var queryParams = new URLSearchParams(window.location.search);

Iterate & Log

for (var q of queryParams) {
  console.log(q);
}

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.delete("job");
queryParams.toString(); // ?id=1&firstName=Bob&hobby=Baseball&hobby=Basketball

Using good ol' Javacsript

Consider the same url:

http://www.systemoutofmemory.com?id=1&firstName=Bob&hobby=Baseball&hobby=Basketball

Get the query string & split

var query = window.location.search.substring(1);
var queryParams = query.split("&");

Getting a query string parameter

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

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


Back to The Programmer Blog