2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to replace plain URLs with links?

The function mentioned below , i am using this to match URLs inside a given text and replace them for HTML links.

function replaceURLWithHTMLLinks(text) {

    var exp = /(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/i;

    return text.replace(exp,"<a href="$1">$1</a>"); 

}

currently I am only replacing the first match. How to replace all the URL?

userimage

Identifying URLs is tricky because they are often surrounded by punctuation marks and because users frequently do not use the full form of the URL. Many JavaScript functions exist for replacing URLs with hyperlinks.

I changed the implementation to prototype the String class so that items can be matched like so:

var text = 'email@domain.com';

text.linkify();

'http://kodetalk.com'.linkify();

Anyway, here's the script:

if(!String.linkify) {

    String.prototype.linkify = function() {

        // http://, https://, ftp://

        var urlPattern = /b(?:https?|ftp)://[a-z0-9-+&@#/%?=~_|!:,.;]*[a-z0-9-+&@#/%=~_|]/gim;

        // www. sans http:// or https://

        var pseudoUrlPattern = /(^|[^/])(www.[S]+(b|$))/gim;

        // Email addresses

        var emailAddressPattern = /[w.]+@[a-zA-Z_-]+?(?:.[a-zA-Z]{2,6})+/gim;

        return this

            .replace(urlPattern, '<a href="$&">$&</a>')

            .replace(pseudoUrlPattern, '$1<a href="http://$2">$2</a>')

            .replace(emailAddressPattern, '<a href="mailto:$&">$&</a>');

    };

}

Answer is