How to obtain the query string from the current URL with JavaScript?

AbdulAziz picture AbdulAziz · Mar 26, 2012 · Viewed 299.3k times · Source

I have URL like this:

http://localhost/PMApp/temp.htm?ProjectID=462

What I need to do is to get the details after the ? sign (query string) - that is ProjectID=462. How can I get that using JavaScript?

What I've done so far is this:

var url = window.location.toString();
url.match(?);

I don't know what to do next.

Answer

Christofer Eliasson picture Christofer Eliasson · Mar 26, 2012

Have a look at the MDN article about window.location.

The QueryString is available in window.location.search.

Solution that work in legacy browsers as well

MDN provide an example (no longer available in the above referenced article) of how to the get value of a single key available in the QueryString. Something like this:

function getQueryStringValue (key) {  
  return decodeURIComponent(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  
}  

// Would write the value of the QueryString-variable called name to the console  
console.log(getQueryStringValue("name")); 

In modern browsers

In modern browsers you have the searchParams property of the URL interface, which returns a URLSearchParams object. The returned object has a number of convenient methods, including a get-method. So the equivalent of the above example would be:

let params = (new URL(document.location)).searchParams;
let name = params.get("name");

The URLSearchParams interface can also be used to parse strings in a querystring format, and turn them into a handy URLSearchParams object.

let paramsString = "name=foo&age=1337"
let searchParams = new URLSearchParams(paramsString);

searchParams.has("name") === true; // true
searchParams.get("age") === "1337"; // true

Notice that the browser support is still limited on this interface, so if you need to support legacy browsers, stick with the first example or use a polyfill.