I am using this function to convert text into clickable links (<a href=""> </a>) and image urls into img tags (<img src="" />).
const parsecontent = (text)=>{
var ishyperlink= /([^\S]|^)((https?\:\/\/)(\S+))/gi;
return (text || "").replace(ishyperlink,
function(match, space, url){
var isimglink = /https?:\/\/.*\.(?:png|jpg|gif|jpeg)/i;
if (url.match(isimglink)) {
return space + '<a href="' + url + '"><img src="' + url + '" /></a>';
}
return space + '<a href="' + url + '">' + url + '</a>';
}
);
}
Using like this
const div = document.querySelector("#content");
div.innerHTML = parsecontent(div.innerHTML);
It works fine, if the content with proper spaces. It links, image urls not separated with spaces it fails. Can you pls help me to fix this?
Codepen here https://codepen.io/dagalti/pen/GRqpYLp
