How to replace plain URLs with links?

前端 未结 24 2355
生来不讨喜
生来不讨喜 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:00

    I made a change to Roshambo String.linkify() to the emailAddressPattern to recognize aaa.bbb.@ccc.ffffd addresses

    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 *** here I've changed the expression ***
            var emailAddressPattern = /(([a-zA-Z0-9_\-\.]+)@[a-zA-Z_]+?(?:\.[a-zA-Z]{2,6}))+/gim;
    
            return this
                .replace(urlPattern, '$&')
                .replace(pseudoUrlPattern, '$1$2')
                .replace(emailAddressPattern, '$1');
        };
    }
    

提交回复
热议问题