How to replace plain URLs with links?

前端 未结 24 2279
生来不讨喜
生来不讨喜 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 05:53

    I had to do the opposite, and make html links into just the URL, but I modified your regex and it works like a charm, thanks :)

    var exp = /<a\s.*href=['"](\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])['"].*>.*<\/a>/ig;
    
    source = source.replace(exp,"$1");
    
    0 讨论(0)
  • 2020-11-21 05:55

    The best script to do this: http://benalman.com/projects/javascript-linkify-process-lin/

    0 讨论(0)
  • 2020-11-21 05:56
    /**
     * Convert URLs in a string to anchor buttons
     * @param {!string} string
     * @returns {!string}
     */
    
    function URLify(string){
      var urls = string.match(/(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)/g);
      if (urls) {
        urls.forEach(function (url) {
          string = string.replace(url, '<a target="_blank" href="' + url + '">' + url + "</a>");
        });
      }
      return string.replace("(", "<br/>(");
    }
    

    simple example

    0 讨论(0)
  • 2020-11-21 05:56

    The warnings about URI complexity should be noted, but the simple answer to your question is:
    To replace every match you need to add the /g flag to the end of the RegEx:
    /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi

    0 讨论(0)
  • 2020-11-21 05:58

    Replace URLs in text with HTML links, ignore the URLs within a href/pre tag. https://github.com/JimLiu/auto-link

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

    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, but I was unable to find one that works as well as the urlize filter in the Python-based web framework Django. I therefore ported Django's urlize function to JavaScript:

    https://github.com/ljosa/urlize.js

    An example:

    urlize('Go to SO (stackoverflow.com) and ask. <grin>', 
           {nofollow: true, autoescape: true})
    => "Go to SO (<a href="http://stackoverflow.com" rel="nofollow">stackoverflow.com</a>) and ask. &lt;grin&gt;"
    

    The second argument, if true, causes rel="nofollow" to be inserted. The third argument, if true, escapes characters that have special meaning in HTML. See the README file.

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