Javascript location get params

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);

Читайте также:  Php mysqli fetch column

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; >

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) < resultJavascript location get params = 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 .

Источник

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) < paramsJavascript location get params = 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!

Источник

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

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

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

Например, вот 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 имеется пробел.

Попробуем использовать этот 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 — значение хеша

Источник

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