<p>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 the first match.</p>

<p>How I can replace all the URL? I guess I should be using the <em>exec</em> command, but I did not really figure how to do it.</p>

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

[{'answer_id': 37687, 'author': 'Sam Hasler', 'author_id': 2541, 'author_profile': 'https://Stackoverflow.com/users/2541', 'pm_score': 8, 'selected': False, 'text': '<h3>Replacing URLs with links (Answer to the General Problem)</h3>\n\n<p>The regular expression in the question misses <em>a lot</em> of edge cases. When detecting URLs, it\'s always better to use a specialized library that handles international domain names, new TLDs like <code>.museum</code>, parentheses and other punctuation within and at the end of the URL, and many other edge cases. See the Jeff Atwood\'s blog post <em><a href="http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html" rel="noreferrer">The Problem With URLs</a></em> for an explanation of some of the other issues. </p>\n\n<blockquote>\n  <p>The <strong>best summary of URL matching libraries</strong> is in <strong><a href="https://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links#21925491">Dan Dascalescu\'s Answer <img src="https://i.stack.imgur.com/AhNsx.png" alt="+100"></a></strong><br>\n  (as of Feb 2014)</p>\n</blockquote>\n\n<hr>\n\n<h3>"Make a regular expression replace more than one match" (Answer to the specific problem)</h3>\n\n<p>Add a "g" to the end of the regular expression to enable global matching:</p>\n\n<pre><code>/ig;\n</code></pre>\n\n<p>But that only fixes the problem in the question where the regular expression was only replacing the first match. <em>Do not use that code.</em></p>\n'}, {'answer_id': 792151, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>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 :) </p>\n\n<pre>\nvar exp = /&lt;a\\s.*href=['&quot;](\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&amp;@#\\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\\/%=~_|])['&quot;].*&gt;.*&lt;\\/a&gt;/ig;\n\nsource = source.replace(exp,&quot;$1&quot;);\n</pre>\n"}, {'answer_id': 2166104, 'author': 'Travis', 'author_id': 252828, 'author_profile': 'https://Stackoverflow.com/users/252828', 'pm_score': 5, 'selected': False, 'text': '<p>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</p>\n\n<p>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):</p>\n\n<pre><code>function Linkify(inputText) {\n    //URLs starting with http://, https://, or ftp://\n    var replacePattern1 = /(\\b(https?|ftp):\\/\\/[-A-Z0-9+&amp;@#\\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\\/%=~_|])/gim;\n    var replacedText = inputText.replace(replacePattern1, \'&lt;a href="$1" target="_blank"&gt;$1&lt;/a&gt;\');\n\n    //URLs starting with www. (without // before it, or it\'d re-link the ones done above)\n    var replacePattern2 = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n    var replacedText = replacedText.replace(replacePattern2, \'$1&lt;a href="http://$2" target="_blank"&gt;$2&lt;/a&gt;\');\n\n    //Change email addresses to mailto:: links\n    var replacePattern3 = /(\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,6})/gim;\n    var replacedText = replacedText.replace(replacePattern3, \'&lt;a href="mailto:$1"&gt;$1&lt;/a&gt;\');\n\n    return replacedText\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n'}, {'answer_id': 2250355, 'author': 'Uwe Keim', 'author_id': 107625, 'author_profile': 'https://Stackoverflow.com/users/107625', 'pm_score': 1, 'selected': False, 'text': '<p>The e-mail detection in Travitron\'s answer above did not work for me, so I extended/replaced it with the following (C# code).</p>\n\n<pre><code>// Change e-mail addresses to mailto: links.\nconst RegexOptions o = RegexOptions.Multiline | RegexOptions.IgnoreCase;\nconst string pat3 = @"([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,6})";\nconst string rep3 = @"&lt;a href=""mailto:$1@$2.$3""&gt;$1@$2.$3&lt;/a&gt;";\ntext = Regex.Replace(text, pat3, rep3, o);\n</code></pre>\n\n<p>This allows for e-mail addresses like "<em>firstname.secondname@one.two.three.co.uk</em>".</p>\n'}, {'answer_id': 3115735, 'author': 'Tiago Fischer', 'author_id': 277619, 'author_profile': 'https://Stackoverflow.com/users/277619', 'pm_score': 3, 'selected': False, 'text': '<p>The best script to do this:\n<a href="http://benalman.com/projects/javascript-linkify-process-lin/" rel="noreferrer">http://benalman.com/projects/javascript-linkify-process-lin/</a></p>\n'}, {'answer_id': 3890175, 'author': 'cloud8421', 'author_id': 470194, 'author_profile': 'https://Stackoverflow.com/users/470194', 'pm_score': 7, 'selected': False, 'text': '<p>I\'ve made some small modifications to Travis\'s code (just to avoid any unnecessary redeclaration - but it\'s working great for my needs, so nice job!):</p>\n\n<pre><code>function linkify(inputText) {\n    var replacedText, replacePattern1, replacePattern2, replacePattern3;\n\n    //URLs starting with http://, https://, or ftp://\n    replacePattern1 = /(\\b(https?|ftp):\\/\\/[-A-Z0-9+&amp;@#\\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\\/%=~_|])/gim;\n    replacedText = inputText.replace(replacePattern1, \'&lt;a href="$1" target="_blank"&gt;$1&lt;/a&gt;\');\n\n    //URLs starting with "www." (without // before it, or it\'d re-link the ones done above).\n    replacePattern2 = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n    replacedText = replacedText.replace(replacePattern2, \'$1&lt;a href="http://$2" target="_blank"&gt;$2&lt;/a&gt;\');\n\n    //Change email addresses to mailto:: links.\n    replacePattern3 = /(([a-zA-Z0-9\\-\\_\\.])+@[a-zA-Z\\_]+?(\\.[a-zA-Z]{2,6})+)/gim;\n    replacedText = replacedText.replace(replacePattern3, \'&lt;a href="mailto:$1"&gt;$1&lt;/a&gt;\');\n\n    return replacedText;\n}\n</code></pre>\n'}, {'answer_id': 7123542, 'author': 'Roshambo', 'author_id': 610051, 'author_profile': 'https://Stackoverflow.com/users/610051', 'pm_score': 6, 'selected': False, 'text': '<p>Made some optimizations to Travis\' <code>Linkify()</code> code above. I also fixed a bug where email addresses with subdomain type formats would not be matched (i.e. example@domain.co.uk).</p>\n\n<p>In addition, I changed the implementation to prototype the <code>String</code> class so that items can be matched like so:</p>\n\n<pre><code>var text = \'address@example.com\';\ntext.linkify();\n\n\'http://stackoverflow.com/\'.linkify();\n</code></pre>\n\n<p>Anyway, here\'s the script:</p>\n\n<pre><code>if(!String.linkify) {\n    String.prototype.linkify = function() {\n\n        // http://, https://, ftp://\n        var urlPattern = /\\b(?:https?|ftp):\\/\\/[a-z0-9-+&amp;@#\\/%?=~_|!:,.;]*[a-z0-9-+&amp;@#\\/%=~_|]/gim;\n\n        // www. sans http:// or https://\n        var pseudoUrlPattern = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n\n        // Email addresses\n        var emailAddressPattern = /[\\w.]+@[a-zA-Z_-]+?(?:\\.[a-zA-Z]{2,6})+/gim;\n\n        return this\n            .replace(urlPattern, \'&lt;a href="$&amp;"&gt;$&amp;&lt;/a&gt;\')\n            .replace(pseudoUrlPattern, \'$1&lt;a href="http://$2"&gt;$2&lt;/a&gt;\')\n            .replace(emailAddressPattern, \'&lt;a href="mailto:$&amp;"&gt;$&amp;&lt;/a&gt;\');\n    };\n}\n</code></pre>\n'}, {'answer_id': 7138764, 'author': 'Christian Koch', 'author_id': 725349, 'author_profile': 'https://Stackoverflow.com/users/725349', 'pm_score': 4, 'selected': False, 'text': '<p>I made a change to Roshambo String.linkify() to the emailAddressPattern to recognize aaa.bbb.@ccc.ddd addresses</p>\n\n<pre><code>if(!String.linkify) {\n    String.prototype.linkify = function() {\n\n        // http://, https://, ftp://\n        var urlPattern = /\\b(?:https?|ftp):\\/\\/[a-z0-9-+&amp;@#\\/%?=~_|!:,.;]*[a-z0-9-+&amp;@#\\/%=~_|]/gim;\n\n        // www. sans http:// or https://\n        var pseudoUrlPattern = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n\n        // Email addresses *** here I\'ve changed the expression ***\n        var emailAddressPattern = /(([a-zA-Z0-9_\\-\\.]+)@[a-zA-Z_]+?(?:\\.[a-zA-Z]{2,6}))+/gim;\n\n        return this\n            .replace(urlPattern, \'&lt;a target="_blank" href="$&amp;"&gt;$&amp;&lt;/a&gt;\')\n            .replace(pseudoUrlPattern, \'$1&lt;a target="_blank" href="http://$2"&gt;$2&lt;/a&gt;\')\n            .replace(emailAddressPattern, \'&lt;a target="_blank" href="mailto:$1"&gt;$1&lt;/a&gt;\');\n    };\n}\n</code></pre>\n'}, {'answer_id': 8443010, 'author': 'Artjom Kurapov', 'author_id': 158448, 'author_profile': 'https://Stackoverflow.com/users/158448', 'pm_score': 3, 'selected': False, 'text': '<p>If you need to show shorter link (only domain), but with same long URL, you can try my modification of Sam Hasler\'s code version posted above</p>\n\n<pre><code>function replaceURLWithHTMLLinks(text) {\n    var exp = /(\\b(https?|ftp|file):\\/\\/([-A-Z0-9+&amp;@#%?=~_|!:,.;]*)([-A-Z0-9+&amp;@#%?\\/=~_|!:,.;]*)[-A-Z0-9+&amp;@#\\/%=~_|])/ig;\n    return text.replace(exp, "&lt;a href=\'$1\' target=\'_blank\'&gt;$3&lt;/a&gt;");\n}\n</code></pre>\n'}, {'answer_id': 10498205, 'author': 'Vebjorn Ljosa', 'author_id': 17498, 'author_profile': 'https://Stackoverflow.com/users/17498', 'pm_score': 4, 'selected': False, 'text': '<p>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 <code>urlize</code> filter in the Python-based web framework Django. I therefore ported Django\'s <code>urlize</code> function to JavaScript:</p>\n\n<blockquote>\n  <p><a href="https://github.com/ljosa/urlize.js" rel="noreferrer">https://github.com/ljosa/urlize.js</a></p>\n</blockquote>\n\n<p>An example:</p>\n\n<pre><code>urlize(\'Go to SO (stackoverflow.com) and ask. &lt;grin&gt;\', \n       {nofollow: true, autoescape: true})\n=&gt; "Go to SO (&lt;a href="http://stackoverflow.com" rel="nofollow"&gt;stackoverflow.com&lt;/a&gt;) and ask. &amp;lt;grin&amp;gt;"\n</code></pre>\n\n<p>The second argument, if true, causes <code>rel="nofollow"</code> to be inserted. The third argument, if true, escapes characters that have special meaning in HTML. See <a href="https://github.com/ljosa/urlize.js/blob/master/README.md" rel="noreferrer">the README file</a>.</p>\n'}, {'answer_id': 13518703, 'author': 'rlemon', 'author_id': 829835, 'author_profile': 'https://Stackoverflow.com/users/829835', 'pm_score': 3, 'selected': False, 'text': '<p>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. </p>\n\n<pre><code> function make_link(string) {\n    var words = string.split(\' \'),\n        ret = document.createDocumentFragment();\n    for (var i = 0, l = words.length; i &lt; l; i++) {\n        if (words[i].match(/[-a-zA-Z0-9@:%_\\+.~#?&amp;//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&amp;//=]*)?/gi)) {\n            var elm = document.createElement(\'a\');\n            elm.href = words[i];\n            elm.textContent = words[i];\n            if (ret.childNodes.length &gt; 0) {\n                ret.lastChild.textContent += \' \';\n            }\n            ret.appendChild(elm);\n        } else {\n            if (ret.lastChild &amp;&amp; ret.lastChild.nodeType === 3) {\n                ret.lastChild.textContent += \' \' + words[i];\n            } else {\n                ret.appendChild(document.createTextNode(\' \' + words[i]));\n            }\n        }\n    }\n    return ret;\n}\n</code></pre>\n\n<p>There are some caveats, namely with older IE and textContent support. </p>\n\n<p><a href="http://jsfiddle.net/rlemon/Npavu/">here</a> is a demo.</p>\n'}, {'answer_id': 19772928, 'author': 'Mike Mestnik', 'author_id': 1153319, 'author_profile': 'https://Stackoverflow.com/users/1153319', 'pm_score': 1, 'selected': False, 'text': '<p>After input from several sources I\'ve now a solution that works well.  It had to do with writing your own replacement code.</p>\n\n<p><a href="https://stackoverflow.com/a/19708150/1153319">Answer</a>.</p>\n\n<p><a href="http://jsfiddle.net/EwzcD/1/" rel="nofollow noreferrer">Fiddle</a>.</p>\n\n<pre><code>function replaceURLWithHTMLLinks(text) {\n    var re = /(\\(.*?)?\\b((?:https?|ftp|file):\\/\\/[-a-z0-9+&amp;@#\\/%?=~_()|!:,.;]*[-a-z0-9+&amp;@#\\/%=~_()|])/ig;\n    return text.replace(re, function(match, lParens, url) {\n        var rParens = \'\';\n        lParens = lParens || \'\';\n\n        // Try to strip the same number of right parens from url\n        // as there are left parens.  Here, lParenCounter must be\n        // a RegExp object.  You cannot use a literal\n        //     while (/\\(/g.exec(lParens)) { ... }\n        // because an object is needed to store the lastIndex state.\n        var lParenCounter = /\\(/g;\n        while (lParenCounter.exec(lParens)) {\n            var m;\n            // We want m[1] to be greedy, unless a period precedes the\n            // right parenthesis.  These tests cannot be simplified as\n            //     /(.*)(\\.?\\).*)/.exec(url)\n            // because if (.*) is greedy then \\.? never gets a chance.\n            if (m = /(.*)(\\.\\).*)/.exec(url) ||\n                    /(.*)(\\).*)/.exec(url)) {\n                url = m[1];\n                rParens = m[2] + rParens;\n            }\n        }\n        return lParens + "&lt;a href=\'" + url + "\'&gt;" + url + "&lt;/a&gt;" + rParens;\n    });\n}\n</code></pre>\n'}, {'answer_id': 21455918, 'author': 'Nishant Kumar', 'author_id': 430803, 'author_profile': 'https://Stackoverflow.com/users/430803', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Reg Ex:</strong> \n<code>/(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&amp;@#\\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\\/%=~_|]*)/ig</code></p>\n\n<pre><code>function UriphiMe(text) {\n      var exp = /(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&amp;@#\\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\\/%=~_|]*)/ig; \n      return text.replace(exp,"&lt;a href=\'$1\'&gt;$1&lt;/a&gt;");\n}\n</code></pre>\n\n<p><strong>Below are some tested string:</strong> </p>\n\n<ol>\n<li>Find me on to www.google.com </li>\n<li>www</li>\n<li>Find me on to www.<a href="http://www.com" rel="nofollow noreferrer">http://www.com</a> </li>\n<li>Follow me on : <a href="http://www.nishantwork.wordpress.com" rel="nofollow noreferrer">http://www.nishantwork.wordpress.com</a> </li>\n<li><a href="http://www.nishantwork.wordpress.com" rel="nofollow noreferrer">http://www.nishantwork.wordpress.com</a> </li>\n<li>Follow me on : <a href="http://www.nishantwork.wordpress.com" rel="nofollow noreferrer">http://www.nishantwork.wordpress.com</a> </li>\n<li><a href="https://stackoverflow.com/users/430803/nishant">https://stackoverflow.com/users/430803/nishant</a></li>\n</ol>\n\n<p>Note: If you don\'t want to pass <code>www</code> as valid one just use below reg ex: \n<code>/(\\b((https?|ftp|file):\\/\\/|(www))[-A-Z0-9+&amp;@#\\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\\/%=~_|])/ig</code></p>\n'}, {'answer_id': 21925491, 'author': 'Dan Dascalescu', 'author_id': 1269037, 'author_profile': 'https://Stackoverflow.com/users/1269037', 'pm_score': 10, 'selected': True, 'text': '<p>First off, rolling your own regexp to parse URLs is a <em>terrible idea</em>. You must imagine this is a common enough problem that someone has written, debugged and <a href="http://benalman.com/code/test/js-linkify/" rel="noreferrer">tested</a> a library for it, according to <a href="https://metacpan.org/pod/Regexp::Common::URI#REFERENCES" rel="noreferrer">the RFCs</a>. <strong>URIs are complex</strong> - check out the <a href="https://github.com/joyent/node/blob/master/lib/url.js" rel="noreferrer">code for URL parsing in Node.js</a> and the Wikipedia page on <a href="http://en.wikipedia.org/wiki/URI_scheme" rel="noreferrer">URI schemes</a>.</p>\n\n<p>There are a ton of edge cases when it comes to parsing URLs: <a href="http://en.wikipedia.org/wiki/Top-level_domain#IDN_test_domains" rel="noreferrer">international domain names</a>, actual (<code>.museum</code>) vs. nonexistent (<code>.etc</code>) TLDs, weird punctuation including <a href="http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html" rel="noreferrer">parentheses</a>, punctuation at the end of the URL, IPV6 hostnames etc.</p>\n\n<p>I\'ve looked at <a href="https://github.com/search?l=JavaScript&amp;q=linkify&amp;ref=cmdform&amp;search_target=global&amp;type=Repositories" rel="noreferrer">a ton</a> of <a href="https://github.com/search?l=JavaScript&amp;q=autolink&amp;ref=cmdform&amp;search_target=global&amp;type=Repositories" rel="noreferrer">libraries</a>, and there are a few worth using despite some downsides:</p>\n\n<ul>\n<li>Soapbox\'s <a href="http://soapbox.github.io/jQuery-linkify/" rel="noreferrer">linkify</a> has seen some serious effort put into it, and <a href="https://github.com/SoapBox/jQuery-linkify/pull/51" rel="noreferrer">a major refactor in June 2015</a> <a href="https://github.com/SoapBox/jQuery-linkify/issues/56" rel="noreferrer">removed the jQuery dependency</a>. It still has <a href="https://github.com/SoapBox/linkifyjs/issues/92" rel="noreferrer">issues with IDNs</a>.</li>\n<li><a href="http://alexcorvi.github.io/anchorme.js/" rel="noreferrer">AnchorMe</a> is a newcomer that <a href="https://github.com/ali-saleem/anchorme.js/issues/2" rel="noreferrer">claims to be faster</a> and leaner. Some <a href="https://github.com/ali-saleem/anchorme.js/issues/1" rel="noreferrer">IDN issues</a> as well.</li>\n<li><a href="https://github.com/gregjacobs/Autolinker.js" rel="noreferrer">Autolinker.js</a> lists features very specifically (e.g. <em>"Will properly handle HTML input. The utility will not change the <code>href</code> attribute inside anchor () tags"</em>). I\'ll thrown some tests at it when a <a href="https://github.com/gregjacobs/Autolinker.js/issues/138" rel="noreferrer">demo becomes available</a>.</li>\n</ul>\n\n<p>Libraries that I\'ve disqualified quickly for this task:</p>\n\n<ul>\n<li>Django\'s urlize <a href="https://github.com/ljosa/urlize.js/pull/18" rel="noreferrer">didn\'t handle certain TLDs properly</a> (here is the official <a href="http://data.iana.org/TLD/tlds-alpha-by-domain.txt" rel="noreferrer">list of valid TLDs</a>. <a href="https://github.com/ljosa/urlize.js/issues/21" rel="noreferrer">No demo</a>.</li>\n<li><a href="https://github.com/bryanwoods/autolink-js/issues/12" rel="noreferrer">autolink-js</a> wouldn\'t detect "www.google.com" without http://, so it\'s not quite suitable for autolinking "casual URLs" (without a scheme/protocol) found in plain text.</li>\n<li><a href="https://github.com/cowboy/javascript-linkify" rel="noreferrer">Ben Alman\'s linkify</a> hasn\'t been maintained since 2009.</li>\n</ul>\n\n<p>If you insist on a regular expression, the most comprehensive is the <a href="https://github.com/component/regexps/blob/master/index.js#L3" rel="noreferrer">URL regexp from Component</a>, though it will falsely detect some non-existent two-letter TLDs by looking at it.</p>\n'}, {'answer_id': 23887643, 'author': 'Andrew Murphy', 'author_id': 2008831, 'author_profile': 'https://Stackoverflow.com/users/2008831', 'pm_score': 2, 'selected': False, 'text': '<p>Keep it simple! Say what you cannot have, rather than what you can have :)</p>\n\n<p>As mentioned above, URLs can be quite complex, especially after the \'?\', and not all of them start with a \'www.\' e.g. <code>maps.bing.com/something?key=!"£$%^*()&amp;lat=65&amp;lon&amp;lon=20</code></p>\n\n<p>So, rather than have a complex regex that wont meet all edge cases, and will be hard to maintain, how about this much simpler one, which works well for me in practise.</p>\n\n<p>Match</p>\n\n<p><code>http(s):// (anything but a space)+</code></p>\n\n<p><code>www. (anything but a space)+</code></p>\n\n<p>Where \'anything\' is <code>[^\'"&lt;&gt;\\s]</code>\n... basically a greedy match, carrying on to you meet a space, quote, angle bracket, or end of line </p>\n\n<p>Also:</p>\n\n<p>Remember to check that it is not already in URL format, e.g. the text contains <code>href="..."</code> or <code>src="..."</code></p>\n\n<p>Add ref=nofollow (if appropriate)</p>\n\n<p>This solution isn\'t as "good" as the libraries mentioned above, but is much simpler, and works well in practise.</p>\n\n<pre><code>if html.match( /(href)|(src)/i )) {\n    return html; // text already has a hyper link in it\n    }\n\nhtml = html.replace( \n            /\\b(https?:\\/\\/[^\\s\\(\\)\\\'\\"\\&lt;\\&gt;]+)/ig, \n            "&lt;a ref=\'nofollow\' href=\'$1\'&gt;$1&lt;/a&gt;" \n            );\n\nhtml = html.replace( \n            /\\s(www\\.[^\\s\\(\\)\\\'\\"\\&lt;\\&gt;]+)/ig, \n            "&lt;a ref=\'nofollow\' href=\'http://$1\'&gt;$1&lt;/a&gt;" \n            );\n\nhtml = html.replace( \n             /^(www\\.[^\\s\\(\\)\\\'\\"\\&lt;\\&gt;]+)/ig, \n            "&lt;a ref=\'nofollow\' href=\'http://$1\'&gt;$1&lt;/a&gt;" \n            );\n\nreturn html;\n</code></pre>\n'}, {'answer_id': 30280085, 'author': 'Vitaly', 'author_id': 1031804, 'author_profile': 'https://Stackoverflow.com/users/1031804', 'pm_score': 2, 'selected': False, 'text': '<p>Correct URL detection with international domains &amp; astral characters support is not trivial thing. <code>linkify-it</code> library builds regex from <a href="https://github.com/markdown-it/linkify-it/blob/master/lib/re.js" rel="nofollow">many conditions</a>, and final size is about 6 kilobytes :) . It\'s more accurate than all libs, currently referenced in accepted answer.</p>\n\n<p>See <a href="http://markdown-it.github.io/linkify-it/" rel="nofollow">linkify-it demo</a> to check live all edge cases and test your ones.</p>\n\n<p>If you need to linkify HTML source, you should parse it first, and iterate each text token separately.</p>\n'}, {'answer_id': 30791827, 'author': 'Jim Liu', 'author_id': 888639, 'author_profile': 'https://Stackoverflow.com/users/888639', 'pm_score': 0, 'selected': False, 'text': '<p>Replace URLs in text with HTML links, ignore the URLs within a href/pre tag. \n<a href="https://github.com/JimLiu/auto-link" rel="nofollow">https://github.com/JimLiu/auto-link</a></p>\n'}, {'answer_id': 35758393, 'author': 'Alex C.', 'author_id': 1620543, 'author_profile': 'https://Stackoverflow.com/users/1620543', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve wrote yet another JavaScript library, it might be better for you since it\'s very sensitive with the least possible false positives, fast and small in size. I\'m currently actively maintaining it so please do test it <a href="http://alexcorvi.github.io/anchorme.js/" rel="nofollow noreferrer">in the demo page</a> and see how it would work for you.</p>\n\n<p>link: <a href="https://github.com/alexcorvi/anchorme.js" rel="nofollow noreferrer">https://github.com/alexcorvi/anchorme.js</a></p>\n'}, {'answer_id': 36202408, 'author': 'degenerate', 'author_id': 482115, 'author_profile': 'https://Stackoverflow.com/users/482115', 'pm_score': 4, 'selected': False, 'text': '<p>I searched on google for anything newer and ran across this one:</p>\n\n<pre><code>$(\'p\').each(function(){\n   $(this).html( $(this).html().replace(/((http|https|ftp):\\/\\/[\\w?=&amp;.\\/-;#~%-]+(?![\\w\\s?&amp;.\\/;#~%"=-]*&gt;))/g, \'&lt;a href="$1"&gt;$1&lt;/a&gt; \') );\n});\n</code></pre>\n\n<p><strong>demo:</strong> <a href="http://jsfiddle.net/kachibito/hEgvc/1/" rel="noreferrer">http://jsfiddle.net/kachibito/hEgvc/1/</a></p>\n\n<p>Works really well for normal links.</p>\n'}, {'answer_id': 36988874, 'author': 'Moritz', 'author_id': 5587737, 'author_profile': 'https://Stackoverflow.com/users/5587737', 'pm_score': 2, 'selected': False, 'text': '<p>The warnings about URI complexity should be noted, but the simple answer to your question is:<br>\nTo replace every match you need to add the <code>/g</code> flag to the end of the RegEx:<br>\n<code>/(\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&amp;@#\\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\\/%=~_|])/gi</code></p>\n'}, {'answer_id': 51499913, 'author': 'Johann', 'author_id': 753632, 'author_profile': 'https://Stackoverflow.com/users/753632', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s my solution:</p>\n\n<pre><code>var content = "Visit https://wwww.google.com or watch this video: https://www.youtube.com/watch?v=0T4DQYgsazo and news at http://www.bbc.com";\ncontent = replaceUrlsWithLinks(content, "http://");\ncontent = replaceUrlsWithLinks(content, "https://");\n\nfunction replaceUrlsWithLinks(content, protocol) {\n    var startPos = 0;\n    var s = 0;\n\n    while (s &lt; content.length) {\n        startPos = content.indexOf(protocol, s);\n\n        if (startPos &lt; 0)\n            return content;\n\n        let endPos = content.indexOf(" ", startPos + 1);\n\n        if (endPos &lt; 0)\n            endPos = content.length;\n\n        let url = content.substr(startPos, endPos - startPos);\n\n        if (url.endsWith(".") || url.endsWith("?") || url.endsWith(",")) {\n            url = url.substr(0, url.length - 1);\n            endPos--;\n        }\n\n        if (ROOTNS.utils.stringsHelper.validUrl(url)) {\n            let link = "&lt;a href=\'" + url + "\'&gt;" + url + "&lt;/a&gt;";\n            content = content.substr(0, startPos) + link + content.substr(endPos);\n            s = startPos + link.length;\n        } else {\n            s = endPos + 1;\n        }\n    }\n\n    return content;\n}\n\nfunction validUrl(url) {\n    try {\n        new URL(url);\n        return true;\n    } catch (e) {\n        return false;\n    }\n}\n</code></pre>\n'}, {'answer_id': 55114398, 'author': 'Moonis Abidi', 'author_id': 7791324, 'author_profile': 'https://Stackoverflow.com/users/7791324', 'pm_score': 2, 'selected': False, 'text': '<p>Try the below function :</p>\n\n<pre><code>function anchorify(text){\n  var exp = /(\\b(https?|ftp|file):\\/\\/[-A-Z0-9+&amp;@#\\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\\/%=~_|])/ig;\n  var text1=text.replace(exp, "&lt;a href=\'$1\'&gt;$1&lt;/a&gt;");\n  var exp2 =/(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n  return text1.replace(exp2, \'$1&lt;a target="_blank" href="http://$2"&gt;$2&lt;/a&gt;\');\n}\n</code></pre>\n\n<p><code>alert(anchorify("Hola amigo! https://www.sharda.ac.in/academics/"));</code></p>\n'}, {'answer_id': 55570404, 'author': 'Rahul Hirve', 'author_id': 7509309, 'author_profile': 'https://Stackoverflow.com/users/7509309', 'pm_score': 1, 'selected': False, 'text': '<p>Try Below Solution</p>\n\n<pre><code>function replaceLinkClickableLink(url = \'\') {\nlet pattern = new RegExp(\'^(https?:\\\\/\\\\/)?\'+\n        \'((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.?)+[a-z]{2,}|\'+\n        \'((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))\'+\n        \'(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+]*)*\'+\n        \'(\\\\?[;&amp;a-z\\\\d%_.~+=-]*)?\'+\n        \'(\\\\#[-a-z\\\\d_]*)?$\',\'i\');\n\nlet isUrl = pattern.test(url);\nif (isUrl) {\n    return `&lt;a href="${url}" target="_blank"&gt;${url}&lt;/a&gt;`;\n}\nreturn url;\n}\n</code></pre>\n'}, {'answer_id': 55575592, 'author': 'Zuhair Taha', 'author_id': 1274894, 'author_profile': 'https://Stackoverflow.com/users/1274894', 'pm_score': 3, 'selected': False, 'text': '<pre><code>/**\n * Convert URLs in a string to anchor buttons\n * @param {!string} string\n * @returns {!string}\n */\n\nfunction URLify(string){\n  var urls = string.match(/(((ftp|https?):\\/\\/)[\\-\\w@:%_\\+.~#?,&amp;\\/\\/=]+)/g);\n  if (urls) {\n    urls.forEach(function (url) {\n      string = string.replace(url, \'&lt;a target="_blank" href="\' + url + \'"&gt;\' + url + "&lt;/a&gt;");\n    });\n  }\n  return string.replace("(", "&lt;br/&gt;(");\n}\n</code></pre>\n\n<p><a href="https://codepen.io/zuhairtaha/pen/NmbGKJ" rel="noreferrer">simple example</a></p>\n'}, {'answer_id': 67165342, 'author': 'majid nazari', 'author_id': 6763995, 'author_profile': 'https://Stackoverflow.com/users/6763995', 'pm_score': 0, 'selected': False, 'text': "<p>worked for me :</p>\n<pre><code>var urlRegex =/(\\b((https?|ftp|file):\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&amp;a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?)/ig;\n\nreturn text.replace(urlRegex, function(url) {\n    var newUrl = url.indexOf(&quot;http&quot;) === -1 ? &quot;http://&quot; + url : url;\n    return '&lt;a href=&quot;' + newUrl + '&quot;&gt;' + url + '&lt;/a&gt;';\n});\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/37684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2138/']