How to use JS to calculate the GET variable that is in the URL? For example:
4 answers
// Выставим нужный URL для теста с помощью History API history.replaceState({}, '', '/test?param=value¶m2=42&keyonly'); // location.search === '?param=value¶m2=42&keyonly' var search = location.search.substr(1) .split('&') // разбиваем на параметры .reduce(function (res, a) { // разбираем пары ключ-значение var t = a.split('='); // нужно декодировать и ключ и значение, значения может не быть res[decodeURIComponent(t[0])] = t.length == 1 ? null : decodeURIComponent(t[1]); return res; }, {}); console.log(search); // {"param":"value","param2":"42","keyonly":null} - onefor a separate separate plus) - ddeadlink
|
You can use URLSearchParams . This example reads all variables.
urlParams = new URLSearchParams(window.location.search); params = {}; urlParams.forEach((p, key) => { params[key] = p; }); Then the data parameter will be available in params.data .
urlParams.get('data')- not? And there stillgetAll. - Qwertiy ♦
|
You can use the location object and its fields to access the url
// www.example.com?data=value console.log(location.href); // www.example.com?data=value console.log(location.search) // ?data=value - oneThose. there's still going to have to break all tags through the & symbol - KOTJlETA
|
function $_GET(key) { var s = window.location.search; s = s.match(new RegExp(key + '=([^&=]+)')); return s ? s[1] : false; }; Then you can get the desired variable from your example via
$_GET('data') With regards to URLSearchParams in one of the answers, I will provide a link to caniuse .
- So-so code. No screening - not for the key, not for the value, not even for the regular. - Qwertiy ♦
|