Convert URL Text into Hyperlink

JavaScript | Как создать ссылку из строки?

В стандарте ECMAScript есть раздел B — «Additional ECMAScript Features for Web Browsers» (Дополнительные возможности ECMAScript для веб-браузеров). В нём есть подраздел B.2.3 — «Additional Properties of the String.prototype Object» (Дополнительные свойства прототипа объекта String).

В подразделе перечислены дополнительные методы, с которыми JavaScript может работать в браузере со строковым типом данных. Большинство этих методов используют абстрактную операцию «CreateHTML» — по сути оборачивают строку нужной HTML-разметкой.

Для создания ссылок из строк используется дополнительный метод «link(url)«. Подраздел B.2.3.10 String.prototype.link ( url )

Видео инструкция

В этом видео приводится пример создания ссылки из строки при помощи JavaScript. Ввод команд осуществляется в консоль браузера Google Chrome. Результат виден сразу.

Практика

Объявим строку и присвоим ей переменную (сохраним в переменную):

Результат вывода в консоль браузера:

Переменная stroka со значением - Скачать фото - JavaScript

Воспользуемся дополнительным методом «link( url )» и обернём данную строку HTML-элементом :

var newStrLink = stroka.link("efim360.ru")

В качестве параметра url мы передали строковое значение:

Результат вывода в консоль браузера:

Строку обернули ссылкой и указали атрибут href - JavaScript

Теперь мы обернули строку «Скачать фото» ссылкой и указали HTML-атрибут href. Но это по-прежнему строка JavaScript (не объект элемента).

Превращение строки в элемент

Для превращения строки в элемент HTML-разметки (в объект JavaScript) необходимо использовать интерфейс DOMParser. Мы хотим, чтобы браузер увидел объект, а не строку. Так нам будет проще извлекать данные из новых объектов при необходимости.

var newStrObject = new DOMParser().parseFromString(newStrLink, "text/xml").documentElement

Результат вывода в консоль браузера:

Преобразование строки с разметкой в объект с элементом HTML - JavaScript

Например теперь мы можем легко получить значение нужного нам атрибута:

Получение значений из HTML-атрибутов - объект JavaScript

Вывод строки на страницу

Можно вывести результат работы на страницу текущего документа:

Ссылка из строки на HTML-странице

Мы успешно вывели созданную из строки ссылку на текущую страницу в браузере.

Ссылки

Стандарт DOM — Интерфейс Document — атрибут documentElement

Источник

Hi! Today let’s see how to convert url text to clickable link using javascript. At times, you may want to turn the plain url text into clickable hyperlink automatically. CMS like WordPress has this feature integrated by default. Also blog commenting systems such as Disqus use this to convert naked url text posted by users into hyperlinks. This feature is quite useful and allows others to link relevant pages across web easily. If you want to implement this feature on your own, you can do so using regular expressions and java script. Here we go!

First let’s create a form interface with a textarea input and a button. User has to enter a bunch of text and click on ‘Convert’ button. Then our JS function will detect URLs from the text and replace the plain URLs with clickable links.

index.html

      

Now we get a form like this,

convert url to hyperlink javascript

JavaScript Function

Next we need to write the java script function that takes up the user input, parse, find and replace the text URLs with hyperlinks with the help of regular expression patterns and return the converted text.

  

Add the above script to the index.html file. The function toHyperlink() will do a two-step pattern match. First it will find the links starting with http / https / ftp / file and replace those with hyperlinked texts. Next it looks for urls that start with www and replace those with clickable links.

Now run the file and enter some plain url text in the box provided and click ‘Convert’.

Our JS function will do its magic and you will see converted text with clickable links below the form.

javascript url text into clickable link

That was all about converting non-clickable url into hyperlink with java script. Regular expression is a powerful weapon and you must make sure to use it properly. I hope you like this tutorial. Feel free to customize the code according to your preferences. And please don’t forget to share it on social networks.

Источник

In this tutorial we are going to discuss how to Convert URL Text Into Clickable HTML Links Using JavaScript. It is very easy to covert the URL text to clickable link and here we are converting the URL text to clickable link with the help of regular expression validation.You May have been observed different links, while posting comments in various blogs and via. these links (Clickable links) you can easily redirect to another page. If the links displayed as a text, then no one will observe you comments and will not get attention from different blogger.

Convert Text URLs into Links Using Javascript : https://goo.gl/JZLKmF

So, We have implemented this with the help of comment box, when user enter any link on textarea field and click on submit button, then it will covert and display text URL to clickable HTML Link.

Check out our blog archive on the topic if you’re looking to learn about Convert URL To Clickable Link Using PHP.

Let see the complete source to convert text URL to Clickable Link:

  • When the comment box is empty and user try to submit the comment then it will display the error message.
  • When any URL provided as input in comment box and user try to submit the comment then it will display clickable link.
   rel="stylesheet" type="text/css" href="design.css">  src="jquery.min.js">   $(document).ready(function()  $("#submitform").on("click", function()  var message = $('textarea').val(); if (message.length == "0")  $(".errorMsg").show(); > else  $("#display-results").prepend("
" + linkify(message) + "
"
); $('textarea').val(""); > >); >); function linkify(text) var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|. ;]*[-A-Z0-9+&@#\/%=~_|])/ig; return text.replace(exp, "$1"); > Convert Text URLs into Links Using Javascript. id="mainbox"> rows="4" cols="65"> class="errorMsg">*Please enter the text. type="button" class="button" id="submitform" value="Submit"> id="display-results">
#mainbox width:500px; padding:5px; margin:0px auto; border-radius: 5px;font-family: arial; line-height: 16px;color: #333333; font-size: 14px; background: #ffffff;rgba(200,200,200,0.7) 0 4px 10px -1px; > #display-results width:500px; padding:5px; margin:10px auto; border-radius: 5px;font-family: arial; line-height: 16px;color: #333333; font-size: 14px; background: #ffffff;rgba(200,200,200,0.7) 0 4px 10px -1px; > #message border: 1px solid #d6d7da; padding:4px; background-color:#e5e5e5; margin-top:10px; > textarea padding: 10px; border: solid 1px #BDC7D8; margin-bottom:3px; > .button  background-color: #00BFFF ; border-color: #3ac162; font-weight: bold; padding: 10px 10px; color: #ffffff; > .errorMsg color: #cc0000; margin-bottom: 5px; display:none; >
 type="text/javascript"> function linkify(text)  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|. ;]*[-A-Z0-9+&@#\/%=~_|])/ig; return text.replace(exp, "$1"); > var text = "welcome to skptricks : http://www.skptricks.com/" ; document.write( linkify(text) ); 

This is all about Convert Text URLs into Links Using Javascript tutorial. In case of any issues please do comment in comment box below.

Источник

Огромное количество способов «заменить адрес ссылки javascript».

Рассмотрим пример изменения адресы в атрибуте href через javascript.

Поместим вовнутрь onclick с функцией.

Далее нам понадобится ссылка, где у нас есть атрибут «href» и обратиться к тегу через id .

Стенд для визуализации процесса замены ссылки в реальном времени.

У нас будет вот такая ссылка :

Чтобы увидеть замену ссылки в реальном времени — нажмите на кнопку «Изменить адрес» и смотрите на адрес выше данной строки.

Пример ссылки с измененным адресом ссылки

И теперь та же самая ссылка уже в коде:

Как заменить текст в ссылке

Возьмем этот же пример, только чуть его модернизируем! Напоминаю, что вы можете взять любой способ onclick и обратиться к тегу

Изменим внутри тега название функции :

В теге ссылки изменим id — должен быть уникальным.

Тестируем замену текста в ссылке :

Замена текста в ссылке и адреса в «href» javascript

И третьим пунктом следим оба скрипта в один, чтобы мы смогли по одном нажатию заменить и текст и адрес ссылки.

javascript заменить текст во всех ссылках

Если мы заменяли текст в определенной ссылке, то почему бы не заменить текст во всех ссылках!?

Сделаем кнопку, чтобы было видно добавление текста ссылкам :

Добавим атрибут style с цветом красный — red

function send_text()
var links = document.querySelectorAll(«a»);
links.forEach(link => link.innerHTML = «Новое содержимое во всех ссылках»;
>)
>
>

Добавим вторую , чтобы изменить содержание текст а ссылки ещё раз.

И две ссылки для наглядности.

Чтобы увидеть изменение текста ссылки, две подопытные ссылки

Кнопки для добавления всем ссылкам атрибута.

javascript заменить адрес во всех ссылках.

Следующим пунктом заменим все адреса ссылок на всей странице!

Чтобы вы могли сделать замену ссылке нажав по кнопке, нам потребуется такая кнопка button + onclick с функцией:

function send_newlink()
var links = document.querySelectorAll(«a»);
links.forEach(link => link.href=»https://google.com»;
>)
>

Результат замены, чтобы протестировать замену ссылок на всей странице нажмите по кнопке, а потом по любой ссылке. либо откройте исследовать элемент и сможете наблюдать в процессе, за любой ссылкой..

Добавим новый адрес во все ссылки

Источник

Читайте также:  Изменение кнопки при клике css
Оцените статью