185

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.

Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43
AbdulAziz
  • 5,868
  • 14
  • 56
  • 77
  • Check this http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript – slash197 Mar 26 '12 at 10:33
  • @Cupcake: That question is about extracting parameters, this here only about getting `location.search` – Bergi Aug 01 '13 at 00:23
  • Voting to reopen, the marked duplicate is a request for a library, whereas this question is about getting js code. – 1615903 Jun 15 '16 at 05:18
  • Possible duplicate of [How to get the value from the GET parameters?](https://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-get-parameters) – Durgpal Singh Oct 30 '17 at 14:49
  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Chamara Abeysekara Apr 25 '20 at 06:38

19 Answers19

368

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.

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
  • Just a note: always use `encodeURIComponent/decodeURIComponent` instead of `escape/unescape` – tsh Sep 26 '16 at 09:43
  • 1
    The first function `getQueryStringValue` for legacy browsers, doesn't work for `?foo=bar&foo1=bar1` If we try to fetch value for `foo`, it returns `empty string`. – Farhan Chauhan Jan 21 '19 at 09:08
  • Old browsers (IE) can use the [polyfill for URLSearchParams](https://github.com/ungap/url-search-params) – Pratyush Jul 12 '19 at 07:01
  • @Pratyush yes I mention that in the answer, with a reference to the more popular and more frequently updated [url-search-params-polyfill](https://www.npmjs.com/package/url-search-params-polyfill) package. – Christofer Eliasson Jul 13 '19 at 07:31
  • `const params = (new URL(url)).searchParams;` works for me. – justthink Sep 03 '21 at 05:50
  • You don't need the extra parens: `new URL(document.location).searchParams` works in Chrome – Carl Walsh May 05 '23 at 04:51
68

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
Starx
  • 77,474
  • 47
  • 185
  • 261
18
decodeURI(window.location.search)
  .replace('?', '')
  .split('&')
  .map(param => param.split('='))
  .reduce((values, [ key, value ]) => {
    values[ key ] = value
    return values
  }, {})
Danny Fenstermaker
  • 914
  • 10
  • 12
  • 1
    Good approach. Thanks. A lit bit fix it tho: replace checks the whole(!) string. we need to remove the first char. removing unnecessary loops. Result: window.location.search window.location.search.substr(1) .split("&") .reduce((acc, param) => { const [key, value] = param.split("="); return { ...acc, [key]: value }; }, {}) – Nikita May 05 '20 at 02:19
10

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');
LeOn - Han Li
  • 9,388
  • 1
  • 65
  • 59
8

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

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
Ankit Kumar Rajpoot
  • 5,188
  • 2
  • 38
  • 32
7

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 'window.location.search'.
// -------------------------------------------------------------------------------------
// 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 || this.search;

        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 (Object.prototype.toString.call(map[i]) !== "[object Array]") {
                        map[i] = [map[i]];
                    }

                    map[i].push(source);
                }

                // 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 = window.location.search;
        }
        else {
            for (i in source) {
                key = "&" + encodeURIComponent(i);

                if (Object.prototype.toString.call(source[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);
    }
}

Enjoy.

roydukkey
  • 3,149
  • 2
  • 27
  • 43
6

You can simply use URLSearchParams().

Lets see we have a page with url:

  • https://example.com/?product=1&category=game

On that page, you can get the query string using window.location.search and then extract them with URLSearchParams() class.

const params = new URLSearchParams(window.location.search)

console.log(params.get('product')
// 1

console.log(params.get('category')
// game

Another example using a dynamic url (not from window.location), you can extract the url using URL object.

const url = new URL('https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest')

console.log(url.search)
// ?v=6xJ27BtlM0c&ab_channel=FliteTest

This is a simple working snippet:

const urlInput = document.querySelector('input[type=url]')
const keyInput = document.querySelector('input[name=key]')
const button = document.querySelector('button')
const outputDiv = document.querySelector('#output')

button.addEventListener('click', () => {
    const url = new URL(urlInput.value)
    const params = new URLSearchParams(url.search)
    output.innerHTML = params.get(keyInput.value)
})
div {
margin-bottom: 1rem;
}
<div>
  <label>URL</label> <br>
  <input type="url" value="https://www.youtube.com/watch?v=6xJ27BtlM0c&ab_channel=FliteTest">
</div>

<div>
  <label>Params key</label> <br>
  <input type="text" name="key" value="v">
</div>

<div>
  <button>Get Value</button>
</div>

<div id="output"></div>
Nurul Huda
  • 1,438
  • 14
  • 12
4

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];
  alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");

here is the fiddle

4
  window.location.href.slice(window.location.href.indexOf('?') + 1);
Vishal P Gothi
  • 987
  • 5
  • 15
3

8 years later, for a one-liner

  const search = Object.fromEntries(new URLSearchParams(location.search));

Down-side, it does NOT work with IE11

To explain

  1. The URLSearchParams interface defines utility methods to work with the query string of a URL. (From , https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
  2. The Object.fromEntries() method transforms a list of key-value pairs into an object. (From, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries)
// For https://caniuse.com/?search=fromEntries
> Object.fromEntries(new URLSearchParams(location.search))
> {search: "fromEntries"}
allenhwkim
  • 27,270
  • 18
  • 89
  • 122
2

You should take a look at the URL API that has helper methods to achieve this in it as the URLSearchParams: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

This is not currently supported by all modern browsers, so don't forget to polyfill it (Polyfill available using https://qa.polyfill.io/).

adriendenat
  • 3,445
  • 1
  • 25
  • 25
2
  var queryObj = {};
   if(url.split("?").length>0){
     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.

m.rohail.akram
  • 350
  • 1
  • 11
Muhammad Danial Iqbal
  • 1,546
  • 1
  • 9
  • 10
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Badacadabra May 29 '17 at 13:35
2

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.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
1

Convert that into array then split with '?'

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

url.split('?')[1];     //ProjectID=462
jsduniya
  • 2,464
  • 7
  • 30
  • 45
1
q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q;
insign
  • 5,353
  • 1
  • 38
  • 35
0

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 http://example.com&this=chicken&that=sandwich. 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', 'http://another-example.com&example=something'); // returns 'something'

Reference

Ajay Kumar
  • 1,314
  • 12
  • 22
0

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: a.search ? a.search : null,
    hash: a.hash ? a.hash : null,
    host: a.host ? a.host : null  
  }
}

console.log( parseUrl(window.location.href) ) //stacksnippet
//to obtain a query
console.log( parseUrl( 'https://example.com?qwery=this').query )
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
0

This will return query parameters as an associative array

var queryParams =[];
var query= document.location.search.replace("?",'').split("&");
for(var i =0; i< query.length; i++)
{
  if(query[i]){
    var temp = query[i].split("=");
    queryParams[temp[0]] = temp[1]
  }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
SANTHOSH.SJ
  • 343
  • 1
  • 4
  • 7
  • Explanations or descriptions should be posted as part of your answer, not as a comment on your answer. I have copied your comment to your answer. – Mark Rotteveel Dec 28 '20 at 11:22
0

For React Native, React, and For Node project, below one is working

yarn add  query-string

import queryString from 'query-string';

const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");

console.log(parsed.offset) will display 10
Rajesh N
  • 6,198
  • 2
  • 47
  • 58