How to replace plain URLs with links?

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

    Replacing URLs with links (Answer to the General Problem)

    The regular expression in the question misses a lot of edge cases. When detecting URLs, it's always better to use a specialized library that handles international domain names, new TLDs like .museum, parentheses and other punctuation within and at the end of the URL, and many other edge cases. See the Jeff Atwood's blog post The Problem With URLs for an explanation of some of the other issues.

    The best summary of URL matching libraries is in Dan Dascalescu's Answer
    (as of Feb 2014)


    "Make a regular expression replace more than one match" (Answer to the specific problem)

    Add a "g" to the end of the regular expression to enable global matching:

    /ig;
    

    But that only fixes the problem in the question where the regular expression was only replacing the first match. Do not use that code.

提交回复
热议问题