- Параметры URL | JavaScript
- Получить строку параметров из URL, href ссылки, строки в JS
- location.search: строка параметров из URL-адреса
- HTMLHyperlinkElementUtils.search: строка параметров из атрибута href ссылки
- HTMLHyperlinkElementUtils.search: строка параметров из произвольной строки
- URLSearchParams : получить, добавить, удалить параметр URL или его значение
- Как закодировать и раскодировать URL
- Варианты применения параметров URL-адреса
- Смена содержимого страницы
- Сбор статистики
- How to Get URL Parameters
- Multiple query values
- How to Get URL parameters in JavaScript
- Get full URL with parameters
- Get query params using URL Object
- Parse URL arguments using regular expression
- Conclusion
- Leave a Comment Cancel reply
- Trending Now
Параметры 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
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
How to Get URL parameters in JavaScript
The following blog post will teach you how to get URL parameters in JavaScript. You’ll see what the data looks like, and learn some of the different ways you can pull URL arguments out. You can also get the URL without parameters.
Most web applications require the client to pass a parameter or a set of parameters that represent different data. These can be for example username, the search term(s), file names, etc.
Normally these are passed by putting them in the address bar after a question mark (?). For example:
http://mywebpage.com/somepage.html?name=john&role=user
In order to extract these parameters from the URL, we need to parse them. Let’s check how to parse it.
Get full URL with parameters
In order to get the full URL with parameters from the browser address bar, we can use window.location object. Let’s check the example below.
Get query params using URL Object
So, there is no built-in function in JavaScript to get URL parameters by name. You can use the API provided by modern browsers. Let’s check the code below:
The output will be 5.
Parse URL arguments using regular expression
You can easily parse URL params using regular expressions. Check out the code below:
; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) < paramsHtml get url parameter = value; >); return params; > console.log( getUrlArgument()["post_id"] );
By using the above code, you can get multiple URL parameters by passing the key name. In the above example, we have passed post_id as key and the above function returned the value 5.
Conclusion
In this blog post, we covered how to get URL parameters in JavaScript. As you can see from the examples given, it’s not difficult at all! We hope that with these tips and tricks under your belt, you’ll be able to solve some of those tricky coding problems more efficiently than before. If you’re still struggling with any questions on getting URL Parameters in JavaScript or want a more detailed guide on using them for different purposes, comment below and I’ll help out as best I can. Happy coding!
About Ashis Biswas
A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.
Leave a Comment Cancel reply
Enjoying the articles? I would appreciate a coffee to help me keep writing and coding!