How to get query string from current url using JavaScript?

I have a url:

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

What do I need to do is get the information after the sign ? (query string) is ProjectID=462 . How can I get this using javascript?

What i have done so far:

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

I do not know what to do next.

+77
javascript query-string
Mar 26 '12 at 10:30
source share
13 answers

Take a look at the MDN article on window.location .

QueryString is available at window.location.search .

A solution that works in older browsers

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

 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, there is a searchParams property of the URL interface that returns a URLSearchParams object. The returned object has a number of convenient methods, including the 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 query string format and convert them to a convenient URLSearchParams object.

 let paramsString = "name=foo&age=1337" let searchParams = new URLSearchParams(paramsString); searchParams.has("name") === true; // true searchParams.get("age") === "1337"; // true 

Please note that browser support in this interface is still limited, so if you need to support older browsers, use the first example or use a polyfill .

+173
Mar 26 2018-12-12T00:
source share

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 
+47
Mar 26 2018-12-12T00:
source share
 decodeURI(window.location.search) .replace('?', '') .split('&') .map(param => param.split('=')) .reduce((values, [ key, value ]) => { values[ key ] = value return values }, {}) 
+8
Jun 07 '18 at 19:11
source share

This will add a global function to access 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.

+7
Nov 19 '12 at 14:33
source share

You can use this function to separate a 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 fiddle

+4
Jun 24 '16 at 4:59
source share
  window.location.href.slice(window.location.href.indexOf('?') + 1); 
+3
Nov 11 '17 at 7:39 on
source share

You can use the search property of a window.location object to retrieve part of the request URL. Note that it includes a question mark (?) In the beginning, just in case, which affects how you are going to analyze it.

+2
Mar 26 '12 at 10:33
source share
  var queryObj = {}; if(url.split("?").length>0){ var queryString = url.split("?")[1]; } 

you now have the query part in queryString

The first replacement will remove all the spaces, the second will replace all the "&" part with "," and finally the third place will replace ":" instead of the signs "=".

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

So, let's say you had a query like abc = 123 & efg = 456 . Now, before parsing, your request is converted to something like {"abc": "123", "efg": "456"}. Now that you analyze this, it will provide you with your request in a json object.

+2
May 29 '17 at 7:15
source share

You should take a look at the API URL, which has helper methods to achieve this in it as 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 using https://qa.polyfill.io/ ).

+1
Mar 01 '17 at 13:24
source share

Convert this to an array, then split with '?'

 var url= 'http://localhost/PMApp/temp.htm?ProjectID=462'; url.split('?')[1]; //ProjectID=462 
+1
Jun 05 '18 at 10:21
source share

Try this

 /** * 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 meaning of this, of both.

 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 URL in the window, you can pass it as the second argument.

 var yetAnotherOne = getQueryString('example', 'http://another-example.com&example=something'); // returns 'something' 

Link

0
Sep 20 '18 at 19:07
source share

If you accidentally use typing and have ROM in your Liberal from 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'); 
0
Jan 08 '19 at 2:17
source share
 q={};location.search.replace(/([^?&=]+)=([^&]+)/g,(_,k,v)=>q[k]=v);q; 
0
Apr 02 '19 at 18:19
source share



All Articles