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.

<a href="" target="_blank" class="mylink" rel="nofollow noopener"></a>
Demo URL Converter:

Converting URLs To 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;');

    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;


<textarea rows="10" cols="75" id="text-val">Online HTML Code Generator CSS, JavaScript, PHP, JQuery,  Multi Color Text Generator </textarea>
<button id="convert">Convert</button>
<p id="preview-text"></p>

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