Plain Text URL to Links with Javascript and Regex

September 6, 2012 — Leave a comment
function linkify(text) {
    var exp = /(\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])))/ig;
    var linkedText = text.replace(exp,'<a href="$1" target="_blank">$1</a>');
    // when user puts in 'www' replace it with 'http://www'
    return linkedText.replace('="www.','="http://www.');
}

Sources:
StackOverflow
John Grubber’s RegEx for URL

Mike

Posts Twitter Facebook

My name is Michael Le, and I am a web developer.

No Comments

Be the first to start the conversation.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.