Javascript URL Text Into Clickable Link

Convert all text URLs into clickable HTML link using javascript

0 Comments
Demo URL Converter:
Demo
1

Converting URL Clickable HTML Link

function convert_url(text, link_attributes_obj) {
    //link_attributes_obj (optional) object {target:'_blank', class:'myLink'}

    //html to text
    text = text.replace(/</g, '&lt;');
    text = text.replace(/>/g, '&gt;');

    var attr = [];
    for (var k in link_attributes_obj) {
        if (k !== 'href') {
            attr.push(k + '="' + link_attributes_obj[k] + '"');
        }
    }

    //URLs starting with http://, https://, or ftp://
    var 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.
    var 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
<textarea rows="10" cols="75" id="text-val">Lorem ipsum dolor sit amet, https://www.html-code-generator.com/ consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, www.html-code-generator.com sunt in culpa qui officia deserunt mollit anim id est laborum.</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>
0 comments
Leave a Reply
hostinger