Collect the value of href, hreflang, rel, target, and type attributes of a link

Today we will show you how to find URLs in string and make a link using JavaScript. Recently I was developing a messaging application where we need to detect the URL from the chat message string and create a clickable HTML link instead of that text. So I am going to share the JavaScript function with you.

Читайте также:  Brackets in python regex

Split this example in two different parts

1. Detect URLs from the string

Here, we’ll use the match method of the string along with the regular expression to detect the URLs in text. This method will provide us the list of the URLs in the array.

detectURLs ( «Visit www.cluemediator.com and subscribe us on https://www.cluemediator.com/subscribe for regular updates.» )

In the next step, we will create a clickable link instead of the URLs. Here, we will use the replace method of the string and that method will be used to create a HTML a tag in the text.

replaceURLs ( «Visit www.cluemediator.com and subscribe us on https://www.cluemediator.com/subscribe for regular updates.» )

That’s it for today.
Thank you for reading. Happy Coding.

You may also like.

How to get current image size (width and height) using JavaScript - Clue Mediator

How to get current image size (width and height) using JavaScript

Automatically refresh or reload a page using JavaScript - Clue Mediator

Automatically refresh or reload a page using JavaScript

Check if a variable is a number in JavaScript - Clue Mediator

Check if a variable is a number in JavaScript

How to generate a Unique ID in JavaScript - Clue Mediator

How to generate a Unique ID in JavaScript

How to create autocomplete places search box using Google Maps in JavaScript - Clue Mediator

How can I check if an object is an array in JavaScript - Clue Mediator

How can I check if an object is an array in JavaScript

2 Responses

Leave a Reply Cancel reply

Search your query

Recent Posts

  • Connect to a MySQL Database Using the MySQL Command: A Comprehensive Guide July 16, 2023
  • Connecting to SSH using a PEM File July 15, 2023
  • How to Add the Body to the Mailto Link July 14, 2023
  • How to Add a Subject Line to the Email Link July 13, 2023
  • How to Create Mail and Phone Links in HTML July 12, 2023

Tags

Join us

Top Posts

Explore the article

We are not simply proficient at writing blog post, we’re excellent at explaining the way of learning which response to developers.

For any inquiries, contact us at [email protected] .

  • We provide the best solution to your problem.
  • We give you an example of each article.
  • Provide an example source code for you to download.
  • We offer live demos where you can play with them.
  • Quick answers to your questions via email or comment.

Clue Mediator © 2023. All Rights Reserved.

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.

Источник

Как разобрать 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 — значение хеша

Источник

Get href value of an anchor tag with JavaScript/jQuery

This post will discuss how to get the href value of an anchor tag in JavaScript and jQuery.

1. Using jQuery

In jQuery, you can use the .prop() method to get the href value of an anchor tag. This is demonstrated below:

JS

HTML

To get the text of an anchor element, use the .text() method.

JS

HTML

2. Using JavaScript

In vanilla JavaScript, you can use the querySelector() , which will return the first anchor tag within the document. Then we can directly access the href property to get the exact value of the href attribute. The following code demonstrates this.

JS

HTML

This can also be done using the getAttribute() method, which gets the value of the href attribute on the specified anchor tag.

JS

HTML

That’s all about getting the href value of an anchor tag in JavaScript and jQuery.

Average rating 4.41 /5. Vote count: 37

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂

This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it

Источник

JavaScript: Collect the value of href, hreflang, rel, target, and type attributes of a link

Here is a sample HTML file with a submit button. Write a JavaScript function to get the value of the href, hreflang, rel, target, and type attributes of the specified link.

     

w3resource

Sample Solution: —

      

w3resource

JavaScript Code:

javascript-dom-exercise-4

Flowchart: JavaScript - Collect the value of href, hreflang, rel, target, and type attributes of a link.Set the background color of a paragraph.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

How to insert an item into an array at a specific index (JavaScript)?

What you want is the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it’s just an insert). In this example we will create an array and add an element to it into index 2:

var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge"; console.log(arr.join()); arr.splice(2, 0, "Lene"); console.log(arr.join());
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

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