How to obtain the query string from the current URL with JavaScript?
Voting to reopen, the marked duplicate is a request for a library, whereas this question is about getting js code.
19 Answers 19
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.
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 .
@Pratyush yes I mention that in the answer, with a reference to the more popular and more frequently updated url-search-params-polyfill package.
Use window.location.search to get everything after ? including ?
var url = window.location.search; url = url.replace("?", ''); // remove the ? alert(url); //alerts ProjectID=462 is your case
decodeURI(window.location.search) .replace('?', '') .split('&') .map(param => param.split('=')) .reduce((values, [ key, value ]) => < values[ key ] = value return values >, <>)
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 Javascript get query param = param.split("="); return < . acc, Javascript get query param: value >; >, <>)
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');
You can use this for direct find value via params name.
const urlParams = new URLSearchParams(window.location.search); const myParam = urlParams.get('myParam');
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" ? "" : " mt24">)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share)" title="">Improve this answer)">edited Sep 22, 2017 at 1:40answered Nov 19, 2012 at 14:33 roydukkeyroydukkey3,1392 gold badges27 silver badges43 bronze badges