JSFiddle - React, Tailwind, and code Playground
HTML
<div id="message">
asdfkals;djfkal;sjdfk;lajsdk;flaj http://www.workssanjose.org/
asdfjklkjhgfdsasdfghjkl
http://www.worksskijhgfdanjose.org/
https://pbs.twimg.com/profile_images/522909800191901697/FHCGSQg0.png
</div>
JavaScript
var yourString=document.getElementById('message').innerHTML;
var count=0;
var urls=yourString.match(/(?:^|[^"'])(\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim);
// Make an array of urls
urls.forEach(function(v,i,a){
var n = yourString.indexOf(v,count); //get location of string
if(v.match(/\.(png|jpg|jpeg|gif)$/)===null){// Check if image
// If link replace yourString with new anchor tag
yourString = strSplice(yourString,n,v.length,'<a href="'+v+'">'+v+'</a>');
count += (v.length*2)+16;// Increase count incase there are multiple of the same url.
}else{
// If link replace yourString with img tag
yourString = strSplice(yourString,n,v.length,'<img src="'+v+'" height="120px;" width="120px;"/>');
count += v.length+14;// Increase count incase there are multiple of the same url.
}
});
// A function to splice strings that I found on another StackOverflow Question.
function strSplice(str, index, count, add) {
return str.slice(0, index) + (add || "") + str.slice(index + count);
}
//Replace the value of your element with your string
document.getElementById('message').innerHTML=yourString;