- Параметры URL | JavaScript
- Получить строку параметров из URL, href ссылки, строки в JS
- location.search: строка параметров из URL-адреса
- HTMLHyperlinkElementUtils.search: строка параметров из атрибута href ссылки
- HTMLHyperlinkElementUtils.search: строка параметров из произвольной строки
- URLSearchParams : получить, добавить, удалить параметр URL или его значение
- Как закодировать и раскодировать URL
- Варианты применения параметров URL-адреса
- Смена содержимого страницы
- Сбор статистики
- Sending parameters to another web page
- 1) Understanding the format of URL’s parameters
- 2) Values are sent from the form, to the server
- Sending data without form
- 3) Extracting data received from the URL in the page
- 4) Updating the page with data received
- 5) Now, testing the script
- How to Get URL Parameters
- Multiple query values
Параметры URL | JavaScript
Если часть URL с параметрами должны быть в индексе, а часть — нет (например, при наличии параметров статистики), то можно Google запретить индексировать страницы прямо в Вебмастере.
Получить строку параметров из URL, href ссылки, строки в JS
location.search: строка параметров из URL-адреса
HTMLHyperlinkElementUtils.search: строка параметров из атрибута href ссылки
Относительная ссылка HTMLHyperlinkElementUtils.search [mozilla.org] -->
HTMLHyperlinkElementUtils.search: строка параметров из произвольной строки
URLSearchParams : получить, добавить, удалить параметр URL или его значение
if ('URLSearchParams' in window) alert('есть контакт');
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); // создать объект URLSearchParams [mozilla.org]/[google.com], значение которого должено быть без знака вопроса alert(params);
var url = new URL('http://shpargalkablog.ru/2016/09/url-parameters-js.html?a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'), urlSearch = url.search.slice(1), // выделить из URL строку с параметрами и удалить первый символ params = new URLSearchParams(urlSearch); alert(params);
var url = new URL('http://shpargalkablog.ru/2016/09/url-parameters-js.html?a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'), urlSearch = url.search; if (urlSearch.indexOf("?") == 0) urlSearch = urlSearch.slice(1); // удалить первый символ ?
(вопросительный знак), если он существует var params = new URLSearchParams(urlSearch); alert(params);
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); alert(Array.from(params).length); // перевести в массив
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); alert(params.toString());
var params = new URLSearchParams(‘a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number’); for(var pair of params.entries())
var params = new URLSearchParams(‘a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number’); for(var key of params.keys())
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'), unique = Array.from(params.keys()).filter(function(e, i, arr) < // функция убирает повторы return arr.indexOf(e) == i; >) alert(unique + " или по отдельности " + unique[0] + " и " + unique[1] + " и " + unique[2]);
var params = new URLSearchParams(‘a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number’); for(var value of params.values())
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); alert(params.getAll('a[]') + " или по отдельности " + params.getAll('a[]')[0] + " и " + params.getAll('a[]')[1] + " и " + params.getAll('a[]')[2] + " и " + params.getAll('a[]')[3]);
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); alert(params.get('a[]'));
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); alert(params.get('d'));
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); var d = params.get('d') || "параметр отсутствует"; alert(d);
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); alert(params.has('a[]'));
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); params.append('с','new'); alert(params);
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); params.set('a[]','new'); alert(params);
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); params.set('a[]','new1'); params.append('a[]','new2'); params.append('a[]','new3'); alert(params);
// условие: заменить пустое значение параметра 'a[]' на 'new' var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'), p = 'a[]', a = params.getAll(p); if (params.has(p)) < params.delete(p); for (var i=0; i'') < params.append(p,'new'); >else < params.append(p,a[i]); >> > alert(params);
var params = new URLSearchParams('a[]=name1&a[]=name2&a[]&a[]=name4&b=tel&c=number'); params.delete('a[]'); alert(params);
Как закодировать и раскодировать URL
// для кодирования параметров var params = encodeURIComponent('http://shpargalkablog.ru/2016/09/url-параметры+js.html'), url = 'http://shpargalkablog.ru/?url=' + params; alert(url); // результат: http://shpargalkablog.ru/?url=http%3A%2F%2Fshpargalkablog.ru%2F2016%2F09%2Furl-%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B%2Bjs.html
// для кодирования параметров var params = new URLSearchParams('url=http://shpargalkablog.ru/2016/09/url-параметры+js.html'), url = 'http://shpargalkablog.ru/?' + params; alert(url); // результат: http://shpargalkablog.ru/?url=http%3A%2F%2Fshpargalkablog.ru%2F2016%2F09%2Furl-%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B+js.html
// для кодирования всего URL var url = encodeURI('http://shpargalkablog.ru/2016/09/url-параметры+js.html'); alert(url); // результат: http://shpargalkablog.ru/2016/09/url-%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B+js.html
var decode = decodeURIComponent('http%3A%2F%2Fshpargalkablog.ru%2F2016%2F09%2Furl-%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B%2Bjs.html'); alert(decode); // результат: http://shpargalkablog.ru/2016/09/url-параметры+js.html
var decode = decodeURI('http%3A%2F%2Fshpargalkablog.ru%2F2016%2F09%2Furl-%D0%BF%D0%B0%D1%80%D0%B0%D0%BC%D0%B5%D1%82%D1%80%D1%8B%2Bjs.html'); alert(decode); // результат: http%3A%2F%2Fshpargalkablog.ru%2F2016%2F09%2Furl-параметры%2Bjs.html
Варианты применения параметров URL-адреса
Передать параметры из формы можно с помощью объекта new FormData в рамках new XMLHttpRequest() ([javascript.ru], полноценный пример). Менять адрес текущей страницы, изменяя параметры URL, можно с помощью Window.history [developer.mozilla.org], чтобы не перезагружать документ.
Смена содержимого страницы
Например, переходя по разным ссылкам, можно увидеть, что изначально помечены галочками разные чебоксы, раскрыты разные уровни дерева:
http://shpargalkablog.ru/2013/08/checked.html?checked[]=21 http://shpargalkablog.ru/2013/08/checked.html?checked[]=1&checked[]=21&checked[]=33
Участок кода, который претерпел изменения:
Сбор статистики
Можно более точно собирать статистику источников переходов на страницу, если сайтам А и Б предложить разные адреса ссылок и считать количество посетителей URL по отдельности (UTM метки)
http://shpargalkablog.ru/2016/09/url-parameters-js.html?site=example1.ru http://shpargalkablog.ru/2016/09/url-parameters-js.html?site=example2.ru
Sending parameters to another web page
For this purpose a form is created whose values will be transmitted automatically, and in the target page, a script retrieves the values sent.
We have seen how to create a form, we will detail here how to extract the transmitted data.
1) Understanding the format of URL’s parameters
Three symbols are used to define a string of parameters to pass:
? concatenates the URL and the string of parameters. & separates multiple parameters. = assigns a value to the variable.
https://www.xul.fr/demo.html?login="me"&password="1234"
In this example, we have two parameters, login and password, which are assigned the values «me» and «1234».
2) Values are sent from the form, to the server
You have nothing to do to send the values: all variables and values in a form are sent automatically providing the action of the form is a page to load.
The attribute «name» of each form item will provide the name of the variable and the attribute «value» its value.
See at the source of the form at bottom.
The GET method appends the data to the URL, while the POST method would transmit them directly.
Sending data without form
To pass parameters to another page or a script without displaying a form (but with a form tag), we use the «hidden» field:
This invisible form will pass to otherpage.html the parameter: varname=12345.
3) Extracting data received from the URL in the page
The location.search attribute contains the chain of parameters, it remains to be analyzed.
Here is the complete code to process data sent:
- location.search is the property that holds the list of parameters.
- substring(1) skips the ? symbol and returns the string minus this sign.
- split(«&») splits the string and returns an array whose elements are the parameters.
- this array is assigned to the «parameters» variable. We can now access individual elements by subscripting the array. Parameters[0] is the first element.
- we have to split again the parameter into another small array that holds the name of the variable and the value.
- in this example, we need only for the value, so we subscript the small array to second item, temp[1].
- the unescape function convert special characters.
- we have assigned the l variable with the login value and the p variable with the password.
- the login is written in the log field thanks to the getElementById method.
- and password to the pass field.
4) Updating the page with data received
In this example, I suppose we want to write the data into the page that is loaded with the parameters.
The login variable has been assigned in the previous code.
Two fields have been defined in the page:
The fields are identified by the id property. To fill them with data we have to use the DOM’s method getElementById(«») and the innerHTML property.
getElementById("log").innerHTML = login;
5) Now, testing the script
Fill the fields below and click on the button.
How to Get URL Parameters
URL parameters or query string parameters are used to send a piece of data from client to server via a URL. They can contain information such as search queries, link referrals, user preferences, etc.
JavaScript has a default class URL used to handle everything about URLs, including the parameters.
You can make a URL instance from any URL string you wish. If you want to access the URL of the current web page a user is browsing, you can use window.location.toLocaleString() . Otherwise, you can use anything like “https://example.com/?product=trousers&color=black&newuser&size=s”.
// using a custom URL string const myUrl1 = new URL("https://example.com/?product=trousers&color=black&newuser&size=s"); // using the current page's URL const myUrl2 = new URL(window.location.toLocaleString());
When you want to access the params of a URL instance like myUrl , you can use myUrl.searchParams.get($PARAM_NAME) . See the example below.
Javascript url search params get method
const urlParams = new URL(«https://example.com/?product=trousers&color=black&newuser&size=s»).searchParams; const product = urlParams.get(‘product’); console.log(product); // product const color = urlParams.get(‘color’) console.log(color); // black const newUser = urlParams.get(‘newuser’) console.log(newUser); // empty string const size = urlParams.get(‘size’); console.log(size); // s
If you want to check if the given parameter exists or not, use: urlParams.has() :
Javascript url search params has method
const urlParams = new URLSearchParams(«https://example.com/?product=trousers&color=black&newuser&size=s»); console.log(urlParams.has(‘size’)); // true console.log(urlParams.has(‘paymentmethod’)); // false
Multiple query values
There are times where multiple values are set for a specific parameter. This situation is common when the client wants to send an array. As the arrays are not directly supported in query parameters, the only way is to set multiple values for a single parameter name, like «https://example.com/?products=trousers&products=shirts». To access all the values set for a specific query name, we use the getAll() method
javascript url search params getAll method