JSFiddle - React, Tailwind, and code Playground

by dnielF

HTML

<div id="text">This is a sample paragraph. It can contain a link to http://google.com or maybe
    even include a direct link to an image, such as http://www.google.com/images/logos/ps_logo2.png.
    Either way, the intent is to transofmr these links (http://www.yahoo.com/) in to a clickable
    or viewable link/image.</div>

<br/>

<div id="result"></div>

JavaScript

function convertUrls(texto){
    var urlRegex = /((\b(https?|ftp|file):\/\/|www)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var result = texto.replace(urlRegex,function(url){
        if (url.match(/\.(jpg|png|gif|bmp)$/i))
            return '<img width="185" src="'+url+'" alt="'+url+'" />';
        else if(url.match(/^(www)/i))
            return '<a href="http://'+url+'">'+url+'</a>';
        return '<a href="'+url+'">'+url+'</a>';
    });
    
    return result;
}

var res = convertUrls(document.getElementById("text").innerHTML);

document.getElementById("result").innerHTML = res;