Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to replace URLs not within a href tag in javascript
    primarykey
    data
    text
    <p>I have a situation where I have text which contains URL links. The links are in 2 forms</p> <ol> <li>www.stackoverflow.com</li> <li>&lt;a href="http://www.stackoverflow.com"&gt;Stack over flow&lt;/a&gt;</li> </ol> <p>I am trying to create a simple function that uses regex that will wrap all links of type <strong>1</strong> with A HREF tag but leaving the other ones already wrapped a lone.</p> <p>I have something like this but not successful.</p> <pre><code>function replaceURLWithHTMLLinks(text) { var exp = /(&lt;(\s*)a(\s)*href.*&gt;.*&lt;\/(\s)*a(\s*)&gt;)/ig; var matches = exp.exec(text); for(var i=0; i &lt; matches.length; i++) { var line = matches[i]; if(!exp.test(line)) { var exp2 = /(\b(?:(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&amp;@#\/%?=~_|$!:,.;]*[-A-Z0-9+&amp;@#\/%=~_|$])|”(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^"\r\n]+”?|’(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^'\r\n]+’?)/ig; text = text.replace("http://",""); text = text.replace(exp2, "&lt;a href=http://$1&gt;$1&lt;/a&gt;"); } } return text; } </code></pre> <p>It's not working but hoping someone could fix it :)</p> <p><strong>EDIT</strong></p> <p>The solution that fixed it, with the help of @MikeM answer</p> <pre><code>function replaceLinksSO(text) { rex = /(&lt;a href=")?(?:https?:\/\/)?(?:(?:www)[-A-Za-z0-9+&amp;@#\/%?=~_|$!:,.;]+\.)+[-A-Za-z0-9+&amp;@#\/%?=~_|$!:,.;]+/ig; return text.replace(rex, function ( $0, $1 ) { if(/^https?:\/\/.+/i.test($0)) { return $1 ? $0: '&lt;a href="'+$0+'"&gt;'+$0+'&lt;/a&gt;'; } else { return $1 ? $0: '&lt;a href="http://'+$0+'"&gt;'+$0+'&lt;/a&gt;'; } }); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload