Plain Text URL to Links with Javascript and Regex
1 min read

Plain Text URL to Links with Javascript and Regex

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