Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract and add link to URLs in string [duplicate]

Possible Duplicate:
How to replace plain URLs with links?

I have several strings that have links in them. For instance:

var str = "I really love this site: http://www.stackoverflow.com"

and I need to add a link tag to that so the str will be:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>

I imagine there would be some regex involved, but I can't get it to work for me with match(). Any other ideas

like image 966
bjork24 Avatar asked Dec 09 '22 11:12

bjork24


2 Answers

That's easy:

str.replace( /(http:\/\/[^\s]+)/gi , '<a href="$1">$1</a>' )

Output:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>
like image 187
Sean Patrick Floyd Avatar answered Dec 31 '22 02:12

Sean Patrick Floyd


function replaceURL(val) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return val.replace(exp,"<a href='$1'>$1</a>"); 
}
like image 43
Pradeep Singh Avatar answered Dec 31 '22 02:12

Pradeep Singh