javascript get GET parameter


You need to get the value of the get parameter "data" from the url, how can this be implemented?

Author: hik, 2015-09-24

4 answers

Property window.location contains a object with the property search - a string starting with a question mark.

E.g. address https://site.com/script?param=val&data=ololo and JS code:

var strGET = window.location.search.replace( '?', ''); 
// в переменной strGET будет строка "param=val&data=ololo"

Then split by character & and by characters =.

Also useful is the f-ya decodeURIComponent() to decode the parameter value from urlencode.

The complete solution for getting all GET parameters in JavaScript can be as follows:

var params = window
    .location
    .search
    .replace('?','')
    .split('&')
    .reduce(
        function(p,e){
            var a = e.split('=');
            p[ decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
            return p;
        },
        {}
    );

console.log( params['data']);
// выведет в консоль значение  GET-параметра data
 16
Author: Sergiks, 2015-09-24 21:43:38

If I understand correctly, what you want to do is

var params = {};

if (window.location.href.match(/.*\?.*/)) {
  for (var i = 0; i < tmp_params.length; i++) {
    var _tmp = window.location.href.replace(/.*\?/,'')
      .split('&')[i]
      .split('=');

    params[_tmp[0]] = _tmp[1];
  }
}

alert(params.data);
 2
Author: installero, 2015-09-26 08:45:03

location.href allows you to get the current page address.

To get the parameter, you can use a regular expression, or use the following hack:

var parser = document.createElement('a');
parser.href = location.href;

Some properties will be available, for example, parser.protocol, parser.hostname, parser.search and the like.

There are also probably libraries for convenient work with URIs.

 2
Author: Fenex, 2018-08-12 16:34:23
let params = (new URL(document.location)).searchParams; 
console.log(params.get("data"));
 1
Author: BlackRockShooter, 2020-06-19 12:28:33