Get url parameter from javascript

How to get URL parameters in javascript

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380
A URL consists of a root and some parameters that carry some data. These parameters are in the key-value pairs and separated by ‘&’ character. Also, the list of parameters and the actual URL are separated by a ‘?’ character.
This list of parameters is called URL parameters or query parameters while the complete string after the ‘?’ character is called query string.

actual or root URL: https://www.google.com
query parameters: enc=en, auth_user=u and lan=fr
query string: ?enc=en&auth_user=u&lan=fr

  1. Create an empty object that will hold the query parameters.
  2. Retrieve the query string using window.location.search.
  3. Remove the starting ‘?’ by using substr function.
  4. Split the remaining string over ‘&’ character.
  5. Loop over the resulting array. Each array item will be a query parameter in key-value pair separated by ‘=’.
  6. Split the query parameter over ‘=’ and add first item as a key and second item as a value to the object initialized in Step 1.
// initialize an empty object let result = {}; // get URL query string let params = window.location.search; // remove the '?' character params = params.substr(1); // split the query parameters let queryParamArray = params.split('&'); // iterate over parameter array queryParamArray.forEach(function(queryParam) { // split the query parameter over '=' let item = queryParam.split('='); result[item[0]] = decodeURIComponent(item[1]); }); // print result object console.log(result);

// initialize an empty object let result = <>; // get URL query string let params = window.location.search; // remove the ‘?’ character params = params.substr(1); // split the query parameters let queryParamArray = params.split(‘&’); // iterate over parameter array queryParamArray.forEach(function(queryParam) < // split the query parameter over '=' let item = queryParam.split('='); result[item[0]] = decodeURIComponent(item[1]); >); // print result object console.log(result);

Above code when executed with a URL https://www.google.com?enc=en&auth_user=u&lan=fr prints the following output

You can use the above code as a function as given below

function getQueryParams() { // initialize an empty object let result = {}; // get URL query string let params = window.location.search; // remove the '?' character params = params.substr(1); let queryParamArray = params.split('&'); // iterate over parameter array queryParamArray.forEach(function(queryParam) { // split the query parameter over '=' let item = queryParam.split("="); result[item[0]] = decodeURIComponent(item[1]); }); // return result object return result; }

function getQueryParams() < // initialize an empty object let result = <>; // get URL query string let params = window.location.search; // remove the ‘?’ character params = params.substr(1); let queryParamArray = params.split(‘&’); // iterate over parameter array queryParamArray.forEach(function(queryParam) < // split the query parameter over '=' let item = queryParam.split("="); result[item[0]] = decodeURIComponent(item[1]); >); // return result object return result; >

Читайте также:  Python разработка gui приложений

Now you can easily call this function and get url parameter value by name as shown below

let parms = getQueryParams(); params('auth_user');

let parms = getQueryParams(); params(‘auth_user’);

Note that decodeURIComponent function is only required when the value of a query parameter is a URL or has characters such as : , / , [ etc.

Method 2
This method uses regular expression to create an object of key-value pairs of query parameters.

var result = {}; window.location.search .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) { result[key] = value; } ); console.log(result);

var result = <>; window.location.search .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) < resultGet url parameter from javascript = value; >); console.log(result);

where replace method is invoked on the query string.
It takes 2 arguments. First argument is the regular expression which matches ? and & characters in the query string.
Second argument is the callback function which is invoked every time the pattern given in the regular expression is matched in the source string.
Thus, the callback function receives a query parameter every time it is invoked and it adds the key-value pair to an object.
Method 3
Use the URLSearchParams constructor and supply the query string as an argument to it. It will return an object of key-value pairs corresponding to the URL query parameters. Example,

const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); // get the required parameter const param = urlParams.get('lan'); // returns the value of parameter 'lan'

const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); // get the required parameter const param = urlParams.get(‘lan’); // returns the value of parameter ‘lan’

URLSearchParams is not supported by InternetExplorer and supported by the following browser versions

Firefox: 29 and above
Chrome: 49 and above
Edge: 17 and above
Opera: 36 and above
Safari: 10.3 and above

Hit the clap below if this post helped you in retrieving url parameters using javascript.

Share if it’s worth .

Источник

Как разобрать URL в JavaScript?

Представляю Вашему вниманию перевод заметки «How to Parse URL in JavaScript: hostname, pathname, query, hash» автора Dmitri Pavlutin.

Унифицированный указатель ресурса или, сокращенно, URL — это ссылка на веб-ресурс (веб-страницу, изображение, файл). URL определяет местонахождения ресурса и способ его получения — протокол (http, ftp, mailto).

Читайте также:  METANIT.COM

Например, вот URL данной статьи:

https://dmitripavlutin.com/parse-url-javascript 

Часто возникает необходимость получить определенные элементы URL. Это может быть название хоста (hostname, dmitripavlutin.com ) или путь (pathname, /parse-url-javascript ).

Удобным способом получить отдельные компоненты URL является конструктор URL() .

В этой статье мы поговорим о структуре и основных компонентах URL.

1. Структура URL

Изображение лучше тысячи слов. На представленном изображении Вы можете видеть основные компоненты URL:

2. Конструктор URL()

Конструктор URL() — это функция, позволяющая разбирать (парсить) компоненты URL:

const url = new URL(relativeOrAbsolute [, absoluteBase]) 

Аргумент relativeOrAbsolute может быть абсолютным или относительным URL. Если первый аргумент — относительная ссылка, то второй аргумент, absoluteBase , является обязательным и представляет собой абсолютный URL — основу для первого аргумента.

Например, инициализируем URL() с абсолютным URL:

const url = new URL('http://example.com/path/index.html') url.href // 'http://example.com/path/index.html' 

Теперь скомбинируем относительный и абсолютный URL:

const url = new URL('/path/index.html', 'http://example.com') url.href // 'http://example.com/path/index.html' 

Свойство href экземпляра URL() возвращает переданную URL-строку.

После создания экземпляра URL() , Вы можете получить доступ к компонентам URL. Для справки, вот интерфейс экземпляра URL() :

Здесь тип USVString означает, что JavaScript должен возвращать строку.

3. Строка запроса (query string)

Свойство url.search позволяет получить строку запроса URL, начинающуюся с префикса ? :

const url = new URL( 'http://example.com/path/index.html?message=hello&who=world' ) url.search // '?message=hello&who=world' 

Если строка запроса отсутствует, url.search возвращает пустую строку (»):

const url1 = new URL('http://example.com/path/index.html') const url2 = new URL('http://example.com/path/index.html?') url1.search // '' url2.search // '' 
3.1. Разбор (парсинг) строки запроса

Вместо получения исходной строки запроса, мы можем получать ее параметры.

Легкий способ это сделать предоставляет свойство url.searchParams . Значением данного свойства является экземпляр интерфейса URLSeachParams.

Объект URLSearchParams предоставляет множество методов для работы с параметрами строки запроса ( get(param), has(param) и т.д.).

Давайте рассмотрим пример:

const url = new Url( 'http://example.com/path/index.html?message=hello&who=world' ) url.searchParams.get('message') // 'hello' url.searchParams.get('missing') // null 

url.searchParams.get(‘message’) возвращает значение параметра message строки запроса.

Доступ к несуществующему параметру url.searchParams.get(‘missing’) возвращает null .

4. Название хоста (hostname)

Значением свойства url.hostname является название хоста URL:

const url = new URL('http://example.com/path/index.html') url.hostname // 'example.com' 

5. Путь (pathname)

Свойство url.pathname содержит путь URL:

const url = new URL('http://example.com/path/index.html?param=value') url.pathname // '/path/index.html' 

Если URL не имеет пути, url.pathname возвращает символ / :

const url = new URL('http://example.com/'); url.pathname; // '/' 

6. Хеш (hash)

Наконец, хеш может быть получен через свойство url.hash :

const url = new URL('http://example.com/path/index.html#bottom') url.hash // '#bottom' 

Если хеш отсутствует, url.hash возвращает пустую строку (»):

const url = new URL('http://example.com/path/index.html') url.hash // '' 

7. Проверка (валидация) URL

При вызове конструктора new URL() не только создается экземпляр, но также осуществляется проверка переданного URL. Если URL не является валидным, выбрасывается TypeError .

Например, http ://example.com не валидный URL, поскольку после http имеется пробел.

Читайте также:  Javascript определить количество дней

Попробуем использовать этот URL:

Поскольку ‘http ://example.com’ неправильный URL, как и ожидалось, new URL(‘http ://example.com’) выбрасывает TypeError .

8. Работа с URL

Такие свойства, как search, hostname, pathname, hash доступны для записи.

Например, давайте изменим название хоста существующего URL с red.com на blue.io :

const url = new URL('http://red.com/path/index.html') url.href // 'http://red.com/path/index.html' url.hostname = 'blue.io' url.href // 'http://blue.io/path/index.html' 

Свойства origin, searchParams доступны только для чтения.

9. Заключение

Конструктор URL() является очень удобным способом разбора (парсинга) и проверки (валидации) URL в JavaScript.

new URL(relativeOrAbsolute, [, absoluteBase] в качестве первого параметра принимает абсолютный или относительный URL. Если первый параметр является относительным URL, вторым параметром должен быть абсолютный URL — основа для первого аргумента.

После создания экземпляра URL() , Вы можете получить доступ к основным компонентам URL:

  • url.search — исходная строка запроса
  • url.searchParams — экземпляр URLSearchParams для получения параметров строки запроса
  • url.hostname — название хоста
  • url.pathname — путь
  • url.hash — значение хеша

Источник

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.

w3docs logo

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() :

w3docs logo

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

w3docs logo

javascript url search params getAll method

Источник

Оцените статью