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

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

The QueryString is available in window.location.search.

If you want a more convenient interface to work with, you can use 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

The URLSearchParams interface is now widely adopted in browsers (95%+ according to Can I Use), but if you do need to support legacy browsers as well, you can use a polyfill.


If you happened to use Typescript and have dom in your the lib of tsconfig.json, you can do:

const url: URL = new URL(window.location.href);
const params: URLSearchParams = url.searchParams;
// get target key/value from URLSearchParams object
const yourParamValue: string = params.get('yourParamKey');

// To append, you can also leverage api to avoid the `?` check 
params.append('newKey', 'newValue');

decodeURI(window.location.search)
  .replace('?', '')
  .split('&')
  .map(param => param.split('='))
  .reduce((values, [ key, value ]) => {
    values[ key ] = value
    return values
  }, {})

Use window.location.search to get everything after ? including ?

Example:

var url = window.location.search;
url = url.replace("?", ''); // remove the ?
alert(url); //alerts ProjectID=462 is your case