- URL.hash
- Синтаксис
- Значение
- Примеры
- Спецификации
- Поддержка браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Как разобрать URL в JavaScript?
- 1. Структура URL
- 2. Конструктор URL()
- 3. Строка запроса (query string)
- 4. Название хоста (hostname)
- 5. Путь (pathname)
- 6. Хеш (hash)
- 7. Проверка (валидация) URL
- 8. Работа с URL
- 9. Заключение
- Methods to Get Hash (#) Value From URL Using JavaScript
- Get URL Hash Using JavaScript location.hash Property
- Get Hash Value From URL String Using URL() Constructor
- Managing the URL Hash with Javascript
- Getting the URL Hash
- Changing the URL Hash
- Detecting Change in Hash of the Current URL
- Get hash from url javascript
- Код получения hash-а javascript при загрузке страницы.
- Пример работы Кода получения hash-а javascript.
- Пример получения hash-а javascript.
- Код с условием есть/нет hash javascript.
- Пример получения и вывода hash javascript
- Пример получения hash-а javascript 2.
- Тестовый стенд для тестирования получения и вывода решетки/якоря/hash-а
URL.hash
Свойство hash интерфейса URL — это строка типа USVString , содержащая символ ‘#’ , после которого идет идентификатор фрагмента URL-адреса.
Фрагмент не кодируется (en-US) . Если URL-адрес не имеет идентификатора фрагмента, то данное свойство содержит пустую строку — «» .
Примечание: Эта возможность доступна в Web Workers
Синтаксис
const string = url.hash url.hash = newHash
Значение
Примеры
const url = new URL('https://developer.mozilla.org/ru/docs/Web/API/URL/href#Examples'); console.log(url.hash); // Выведет: '#Examples'
Спецификации
Поддержка браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 17 июл. 2023 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Как разобрать 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 — значение хеша
Methods to Get Hash (#) Value From URL Using JavaScript
We can get the hash value from a URL in JavaScript and determine the position on a web page. You can follow different methods to obtain the value.
JavaScript has the location.hash property that can get the hash value or set a new value to the current URL. To extract the hash from a URL string, there is a URL() constructor. It takes the string and returns an object that contains the hash as its property.
I will show you both of these methods to obtain the URL hash using JavaScript in this article. You can use them in different situations.
Get URL Hash Using JavaScript location.hash Property
We have access to the location object in JavaScript. This object has a hash property that will give you the hash value from the current URL in your browser.
It also has the ability to set a new value. That means, we can add or change the URL hash value using JavaScript without reloading the web page with this property.
const hash = location.hash; console.log(hash); // Returns "#reviews" if the current URL is https://example.com/post#reviews
This property returns the value including the pound sign (#) from the current URL. If you want to remove the pound sign and get only the value, you can go it using the substring() method in JavaScript.
const hash = location.hash.substring(1); console.log(hash); // Returns "reviews" if the current URL is https://example.com/post#reviews
When I add the substring() method with «1» as its parameter, it removes the pound sign (#) from the string. In this way, we receive the actual value from the URL.
Get Hash Value From URL String Using URL() Constructor
When we want to get the hash value from a URL string, the location object will not work. Because this object only contains information about the current URL in the browser.
You need to use the URL() constructor function available in JavaScript. When we pass a string URL to this constructor, it will return an object will all the information about that URL.
const url = "https://example.com/post#reviews"; const urlObj = new URL(url); const hash = urlObj.hash; console.log(hash); // #reviews
I am extracting the hash value from the url string using URL() constructor. The object we get from this constructor has a hash property.
This property will contain the value. It will also return the hash value including the pound sign (#) from the url string. Now, you can use it in your project.
For example, you can add it and change the current URL using JavaScript without reloading the web page.
Managing the URL Hash with Javascript
The Javascript URL object can be used to get and set hash value of a given url. To detect a change in hash in the current url, the hashchange event can be listened to.
Getting the URL Hash
The hash of a url can be found by creating a new URL Javascript object from the URL string, and then using its hash property to get the value of the hash fragment. Note that this will include the # character also.
If the url does not contains a hash, then an empty string «» will be returned.
var some_url = 'https://usefulangle.com/posts?123#slider' var hash = new URL(some_url).hash; // "#slider" console.log(hash);
// document.URL refers to the current url var hash = new URL(document.URL).hash; console.log(hash);
Changing the URL Hash
var some_url = 'https://usefulangle.com/posts?123#slider' var url_ob = new URL(some_url); url_ob.hash = '#reviews'; // new url string var new_url = url_ob.href; // "https://usefulangle.com/posts?123#reviews" console.log(new_url);
// document.URL is the current url var url_ob = new URL(document.URL); url_ob.hash = '#345'; // new url var new_url = url_ob.href; // change the current url document.location.href = new_url;
Note that this will not cause a reload of the page.
Detecting Change in Hash of the Current URL
The window.hashchange event can be listened to know when the hash fragment in the current url changes.
window.addEventListener('hashchange', function() < // new hash value console.log(new URL(document.URL).hash); >);
Get hash from url javascript
С помощью javascript можно получить и вывести «якорь/решетку/hash» на экран. Для этого вам понадобится:
Передать полученную строку в объект URL.
И далее получить из созданного объекта ваш «hash».
И выведем на экран с помощью document.write();
Код получения hash-а javascript при загрузке страницы.
Данный код «получения hash-а» будет срабатывать только при загрузке, перезагрузки страницы.
var urlObj = new URL(window.location.href);
document.write (urlObj . hash);
Пример работы Кода получения hash-а javascript.
Если при загрузке страницы «hash» не существовал, то вы ничего не увидите. здесь получается довольно скучно!
Иначе. вы увидите полученный «hash».
Пример получения hash-а javascript.
Если выше вы не получили и не увидели «hash» и. получилось довольно скучно!
Напишем пример, который изменит положение вещей!
Для этого вам понадобится:
Теория и код из выше приведенного пункта — изменим его, чтобы было чуть-чуть интереснее.
Составим условие по которому. в зависимости от того, если/нет «hash» в строке будем выводить разную информацию!
Код с условием есть/нет hash javascript.
urlObj = new URL(window.location.href);
document.write (urlObj . hash); example_hash.innerHTML = «
Пример получения и вывода hash javascript
Разместим выше приведенный код прямо здесь:
Пример получения hash-а javascript 2.
Второй пример основан на предыдущем пункте. только чуть посложнее и без открытия страницы в новом окне.
Не буду описывать процесс получения и вывод построчно — придется писать отдельную страницу. протестируй стенд.
Ниже стенда сможешь скопировать код.
Тестовый стенд для тестирования получения и вывода решетки/якоря/hash-а
Сделал отдельную кнопку, которая позволит увидеть адресную строку с hash и далее получить и вывести его.