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

I have URL like this:


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();

I don't know what to do next.


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

This will add a global function to access to the queryString variables as a map.

// -------------------------------------------------------------------------------------
// Add function for 'window.location.query( [queryString] )' which returns an object
// of querystring keys and their values. An optional string parameter can be used as
// an alternative to ''.
// -------------------------------------------------------------------------------------
// Add function for 'window.location.query.makeString( object, [addQuestionMark] )'
// which returns a queryString from an object. An optional boolean parameter can be
// used to toggle a leading question mark.
// -------------------------------------------------------------------------------------
if (!window.location.query) {
    window.location.query = function (source) {
        var map = {};
        source = source ||;

        if ("" != source) {
            var groups = source, i;

            if (groups.indexOf("?") == 0) {
                groups = groups.substr(1);

            groups = groups.split("&");

            for (i in groups) {
                source = groups[i].split("=",
                    // For: xxx=, Prevents: [xxx, ""], Forces: [xxx]
                    (groups[i].slice(-1) !== "=") + 1

                // Key
                i = decodeURIComponent(source[0]);

                // Value
                source = source[1];
                source = typeof source === "undefined"
                    ? source
                    : decodeURIComponent(source);

                // Save Duplicate Key
                if (i in map) {
                    if ([i]) !== "[object Array]") {
                        map[i] = [map[i]];


                // Save New Key
                else {
                    map[i] = source;

        return map;

    window.location.query.makeString = function (source, addQuestionMark) {
        var str = "", i, ii, key;

        if (typeof source == "boolean") {
            addQuestionMark = source;
            source = undefined;

        if (source == undefined) {
            str =;
        else {
            for (i in source) {
                key = "&" + encodeURIComponent(i);

                if ([i]) !== "[object Array]") {
                    str += key + addUndefindedValue(source[i]);
                else {
                    for (ii = 0; ii < source[i].length; ii++) {
                        str += key + addUndefindedValue(source[i][ii]);

        return (addQuestionMark === false ? "" : "?") + str.substr(1);

    function addUndefindedValue(source) {
        return typeof source === "undefined"
            ? ""
            : "=" + encodeURIComponent(source);



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');
  window.location.href.slice(window.location.href.indexOf('?') + 1);
  var queryObj = {};
     var queryString = url.split("?")[1];

now you have the query part in queryString

First replace will remove all the white spaces, second will replace all the '&' part with "," and finally the third replace will put ":" in place of '=' signs.

queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')

So let say you had a query like abc=123&efg=456. Now before parsing, your query is being converted into something like {"abc":"123","efg":"456"}. Now when you will parse this, it will give you your query in json object.


Convert that into array then split with '?'

var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';

url.split('?')[1];     //ProjectID=462

Try this one

 * Get the value of a querystring
 * @param  {String} field The field to get the value of
 * @param  {String} url   The URL to get the value from (optional)
 * @return {String}       The field value
var getQueryString = function ( field, url ) {
    var href = url ? url : window.location.href;
    var reg = new RegExp( '[?&]' + field + '=([^&#]*)', 'i' );
    var string = reg.exec(href);
    return string ? string[1] : null;

Let’s say your URL is You want to get the value of this, that, and another.

var thisOne = getQueryString('this'); // returns 'chicken'
var thatOne = getQueryString('that'); // returns 'sandwich'
var anotherOne = getQueryString('another'); // returns null

If you want to use a URL other than the one in the window, you can pass one in as a second argument.

var yetAnotherOne = getQueryString('example', ''); // returns 'something'



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

The QueryString is available in

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( RegExp("^(?:.*[&\\?]" + encodeURIComponent(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));  

// Would write the value of the QueryString-variable called name to the console  

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.


Use to get everything after ? including ?


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

You can use this function, for split string from ?id=

 function myfunction(myvar){
  var urls = myvar;
  var myurls = urls.split("?id=");
  var mylasturls = myurls[1];
  var mynexturls = mylasturls.split("&");
  var url = mynexturls[0];

here is the fiddle


You can use the search property of the window.location object to obtain the query part of the URL. Note that it includes the question mark (?) at the beginning, just in case that affects how you intend to parse it.


You should take a look at the URL API that has helper methods to achieve this in it as the URLSearchParams:

This is not currently supported by all modern browsers, so don't forget to polyfill it (Polyfill available using


You can use this for direct find value via params name.

const urlParams = new URLSearchParams(;
const myParam = urlParams.get('myParam');

I think it is way more safer to rely on the browser than any ingenious regex:

const parseUrl = function(url) { 
  const a = document.createElement('a')
  a.href = url
  return {
    protocol: a.protocol ? a.protocol : null,
    hostname: a.hostname ? a.hostname : null,
    port: a.port ? a.port : null,
    path: a.pathname ? a.pathname : null,
    query: ? : null,
    hash: a.hash ? a.hash : null,
    host: ? : null  

console.log( parseUrl(window.location.href) ) //stacksnippet
//to obtain a query
console.log( parseUrl( '').query )


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.