javascript get GET parameter
You need to get the value of the get parameter "data" from the url, how can this be implemented?
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
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);
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.
let params = (new URL(document.location)).searchParams;
console.log(params.get("data"));