Aug 12
Converting a URL into a Link in JavaScript - Linkify Function
I previously implemented something similar in C#, and now I have it in JavaScript. Pass in a bunch of text and get it back with the URLs converted into clickable links (<a />'s).
function linkify(text){
if (text) {
text = text.replace(
/((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
function(url){
var full_url = url;
if (!full_url.match('^https?:\/\/')) {
full_url = 'http://' + full_url;
}
return '<a href="' + full_url + '">' + url + '</a>';
}
);
}
return text;
}
blog comments powered by Disqus