I have a paragraph containing running text that may also contain URLs. The paragraph would contain running text describing an object or thing and interleaved with URLs in between. The URLs could be of the form of
- http://mail.google.com
- http://www.google.com
- www.google.com
I need to parse the paragraph using JavaScript and generate an HTML content, making sure that the URLs are rendered as an HTML anchor. I could use following -
var httpUrlPattern = /https?:\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/\$~+#-]*[\w@?^=%&\/~+#-])?
text = text.replace( httpUrlPattern, '<a href="$&" target="_blank">$&</a>' );
This works fine for URLs of type #1) and #2). But for #3) it generates href=/www.google.com
so I apply additional filtering
var wwwUrlPattern = /(www\.)[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/\$~+#-]*[\w@?^=%&\/~+#-])?;
text = text.replace( wwwUrlPattern, '<a href="http://$&" target="_blank">$&</a>' );
This fixes #3) but breaks #2).
Any suggestion how can I fix all the scenarios?