SO - 30294890
by Arun P Johny
JavaScript
$(function () {
console.log(searchLinks("Sample text https://www.google.fi/images/srpr/logo11w.png and http://google.com/ <a href='http://bing.com/'>http://bing.com/</a>"));
});
function searchLinks(html) {
var $tmp = $('<div />', {
html: html
});
var urlRegex = /\bhttps?:\/\/[a-zA-Z0-9()^=+*@&%#|~?!;:,.-_\/]*[-A-Za-z0-9+&@#\/%=~_()|](?!(\<\/a\>|"|'))/g;
$tmp.contents().each(function () {
if (this.nodeType == Node.TEXT_NODE) {
var string = this.nodeValue;
string = string.replace(urlRegex, function (url) {
if (url.match(/\.gifv/) != null) { //gifv
return gifvToVideo(url);
} else if (url.match(/\.(jpeg|jpg|gif|png|svg)/) != null) { //image
return "<img src='" + url + "' alt='" + url + "'>";
} else if (url.match(/\.(mp4|webm)/) != null) { //video
return '<video><source src="' + url + '"></video>';
} else { //link
return '<a href="' + url + '" target="_blank">' + url + '</a>';
}
});
$(this).replaceWith(string)
}
})
return $tmp.html();
}