regex to match all keyowrds in a string

Being noob in regex I require some support from community

Let say I have this string str

  1. www.anysite.com hello demo try this link
  2. anysite.com indeed demo link
  3. http://www.anysite.com another one
  4. www.anysite.com
  5. http://anysite.com

Consider 1-5 as whole string str here

I want to convert all 'anysite.com' into clickable html links, for which I am using:

str =  str.replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1" target="_blank">$1</a>'); 

This converts all space separated words starting with http/https/ftp into links as

<a href="url" target="_blank">url</a> 

Now to convert all www.anysite.com into links I again used

str = str.replace(/(\b^(http|https|ftp)?(www\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="https://$1" target="_blank">$1</a>'); 

Though it only converts www.anysite.com into link if it is found at very beginning of str. So it convert line number 1 but not line number 4.

Note that I have used ^(http|https|ftp)?(www.) to find all www not starting with http/https/ftp, as for http they already have been converted

Also the link on line number 2, where it is neither started with http nor www rather it ends with .com, how the regex would be for that.

For reference you can try posting this whole string to you facebook timeline, it convert all five line into links. Check snapshot

regex to match all keyowrds in a string

Replay

Category: javascript Time: 2016-07-28 Views: 0

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.271 (s). 12 q(s)