How to replace plain URLs with links?

前端 未结 24 2350
生来不讨喜
生来不讨喜 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, '<a target="_blank" href="$&">$&</a>')
                .replace(pseudoUrlPattern, '$1<a target="_blank" href="http://$2">$2</a>')
                .replace(emailAddressPattern, '<a target="_blank" href="mailto:$1">$1</a>');
        };
    }
    
    0 讨论(0)
  • 2020-11-21 06:00

    Reg Ex: /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig

    function UriphiMe(text) {
          var exp = /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig; 
          return text.replace(exp,"<a href='$1'>$1</a>");
    }
    

    Below are some tested string:

    1. Find me on to www.google.com
    2. www
    3. Find me on to www.http://www.com
    4. Follow me on : http://www.nishantwork.wordpress.com
    5. http://www.nishantwork.wordpress.com
    6. Follow me on : http://www.nishantwork.wordpress.com
    7. https://stackoverflow.com/users/430803/nishant

    Note: If you don't want to pass www as valid one just use below reg ex: /(\b((https?|ftp|file):\/\/|(www))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig

    0 讨论(0)
  • 2020-11-21 06:01

    I searched on google for anything newer and ran across this one:

    $('p').each(function(){
       $(this).html( $(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> ') );
    });
    

    demo: http://jsfiddle.net/kachibito/hEgvc/1/

    Works really well for normal links.

    0 讨论(0)
  • 2020-11-21 06:01

    This solution works like many of the others, and in fact uses the same regex as one of them, however in stead of returning a HTML String this will return a document fragment containing the A element and any applicable text nodes.

     function make_link(string) {
        var words = string.split(' '),
            ret = document.createDocumentFragment();
        for (var i = 0, l = words.length; i < l; i++) {
            if (words[i].match(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi)) {
                var elm = document.createElement('a');
                elm.href = words[i];
                elm.textContent = words[i];
                if (ret.childNodes.length > 0) {
                    ret.lastChild.textContent += ' ';
                }
                ret.appendChild(elm);
            } else {
                if (ret.lastChild && ret.lastChild.nodeType === 3) {
                    ret.lastChild.textContent += ' ' + words[i];
                } else {
                    ret.appendChild(document.createTextNode(' ' + words[i]));
                }
            }
        }
        return ret;
    }
    

    There are some caveats, namely with older IE and textContent support.

    here is a demo.

    0 讨论(0)
  • 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, '<a href="$&">$&</a>')
                .replace(pseudoUrlPattern, '$1<a href="http://$2">$2</a>')
                .replace(emailAddressPattern, '<a href="mailto:$&">$&</a>');
        };
    }
    
    0 讨论(0)
  • 2020-11-21 06:07

    Thanks, this was very helpful. I also wanted something that would link things that looked like a URL -- as a basic requirement, it'd link something like www.yahoo.com, even if the http:// protocol prefix was not present. So basically, if "www." is present, it'll link it and assume it's http://. I also wanted emails to turn into mailto: links. EXAMPLE: www.yahoo.com would be converted to www.yahoo.com

    Here's the code I ended up with (combination of code from this page and other stuff I found online, and other stuff I did on my own):

    function Linkify(inputText) {
        //URLs starting with http://, https://, or ftp://
        var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
        var replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
    
        //URLs starting with www. (without // before it, or it'd re-link the ones done above)
        var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
        var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
    
        //Change email addresses to mailto:: links
        var replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
        var replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
    
        return replacedText
    }
    

    In the 2nd replace, the (^|[^/]) part is only replacing www.whatever.com if it's not already prefixed by // -- to avoid double-linking if a URL was already linked in the first replace. Also, it's possible that www.whatever.com might be at the beginning of the string, which is the first "or" condition in that part of the regex.

    This could be integrated as a jQuery plugin as Jesse P illustrated above -- but I specifically wanted a regular function that wasn't acting on an existing DOM element, because I'm taking text I have and then adding it to the DOM, and I want the text to be "linkified" before I add it, so I pass the text through this function. Works great.

    0 讨论(0)
提交回复
热议问题