- JavaScript | Как создать ссылку из строки?
- Видео инструкция
- Практика
- Превращение строки в элемент
- Вывод строки на страницу
- Ссылки
- Convert URL Text to Clickable Link using JavaScript
- Converting Plain URL into Clickable Link
- index.html
- Convert URL Text to Clickable Link | Demo
- JavaScript Function
- Convert Text URLs into Links Using Javascript
- Html link text javascript
- Стенд для визуализации процесса замены ссылки в реальном времени.
- Пример ссылки с измененным адресом ссылки
- Как заменить текст в ссылке
- Тестируем замену текста в ссылке :
- Замена текста в ссылке и адреса в «href» javascript
- javascript заменить текст во всех ссылках
- Кнопки для добавления всем ссылкам атрибута.
- javascript заменить адрес во всех ссылках.
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. Результат виден сразу.
Практика
Объявим строку и присвоим ей переменную (сохраним в переменную):
Результат вывода в консоль браузера:
Воспользуемся дополнительным методом «link( url )» и обернём данную строку HTML-элементом :
var newStrLink = stroka.link("efim360.ru")
В качестве параметра url мы передали строковое значение:
Результат вывода в консоль браузера:
Теперь мы обернули строку «Скачать фото» ссылкой и указали HTML-атрибут href. Но это по-прежнему строка JavaScript (не объект элемента).
Превращение строки в элемент
Для превращения строки в элемент HTML-разметки (в объект JavaScript) необходимо использовать интерфейс DOMParser. Мы хотим, чтобы браузер увидел объект, а не строку. Так нам будет проще извлекать данные из новых объектов при необходимости.
var newStrObject = new DOMParser().parseFromString(newStrLink, "text/xml").documentElement
Результат вывода в консоль браузера:
Например теперь мы можем легко получить значение нужного нам атрибута:
Вывод строки на страницу
Можно вывести результат работы на страницу текущего документа:
Мы успешно вывели созданную из строки ссылку на текущую страницу в браузере.
Ссылки
Стандарт DOM — Интерфейс Document — атрибут documentElement
Convert URL Text to Clickable Link using JavaScript
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!
Converting Plain URL into Clickable Link
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
Convert URL Text to Clickable Link | Demo
Now we get a form like this,
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.
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.
Convert Text URLs into Links Using Javascript
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.
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">