Convert Text URLs To Clickable HTML Links Using JavaScript
Using JavaScript convert all text URLs to clickable HTML links. find the text of all URLs in the paragraph or text content and convert it to a clickable HTML link.
Example https://www.html-code-generator.com/
<a href="https://www.html-code-generator.com/" target="_blank" class="mylink" rel="nofollow noopener">https://www.html-code-generator.com/</a>
Demo URL Converter
Demo
Javascript Converting URLs To Clickable HTML Link
const convert_url = (text, link_attributes_obj = {}) => {
//link_attributes_obj (optional) object {target:'_blank', class:'myLink'}
//html to text
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
let attr = [];
for (let k in link_attributes_obj) {
if (k !== 'href') {
attr.push(k + '="' + link_attributes_obj[k].replaceAll(/"/g, "'") + '"');
}
}
//URLs starting with http://, https://, or ftp://
let exp = /((?:https?|ftp):\/\/[a-zA-Z0-9][\w+\d+&@\-#\/%?=~_|!:,.;+]*)/gim;
text = text.replace(exp, '<a href="$1" ' + attr.join(' ') + '>$1</a>');
//URLs starting with www.
let reg_ww = /(?<!\/)(www\.[a-zA-Z0-9][\w+\d+&@\-#\/%?=~_|!:,.;+]*)/gim;
text = text.replace(reg_ww, '<a href="https://$1" ' + attr.join(' ') + '>$1</a>');
return text;
};
Usage ULR to clickable link
<textarea rows="10" cols="75" id="text-val">Online HTML Code Generator CSS, JavaScript, PHP, JQuery, https://www.html-code-generator.com/ Multi Color Text Generator www.html-code-generator.com/html/rainbow-text-generator </textarea>
<button id="convert">Convert</button>
<p id="preview-text"></p>
<script>
document.getElementById("convert").onclick = function(){
let text = document.getElementById("text-val").value;
let link_attributes = {
target: '_blank',
class: 'mylink',
rel: 'nofollow noopener'
};
let result = convert_url(text, link_attributes);
document.getElementById("preview-text").innerHTML= result
}
</script>