Automagically Convert Text to Hyperlinks

This is a function that will take a block of text and wrap hyperlink tags around anything that it recognizes as a link. It supports email addresses and anything that starts with http://, https:// or www.

It is implemented in Javascript but the regular expression code should be pretty universal.

function automagic_link(str) {
    str = str.replace(/([^@ ]+)(@)([A-Za-z0-9.-]+)/gi, '$1@$3');
    str = str.replace(/((http(s?):\/\/)|(www.))+([A-Za-z0-9./&=#?-~%;]+)/gi, 'http$3://$4$5');

    return str;
}

Leave a Reply

{
}