How to replace plain URLs with links?

前端 未结 24 2293
生来不讨喜
生来不讨喜 2020-11-21 05:42

I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing t

24条回答
  •  难免孤独
    2020-11-21 06:05

    Made some optimizations to Travis' Linkify() code above. I also fixed a bug where email addresses with subdomain type formats would not be matched (i.e. example@domain.co.uk).

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

    var text = 'address@example.com';
    text.linkify();
    
    'http://stackoverflow.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, '$&')
                .replace(pseudoUrlPattern, '$1$2')
                .replace(emailAddressPattern, '$&');
        };
    }
    

提交回复
热议问题