-2

Possible Duplicate:
How to extract text from Link in Javascript?

I want to extract a hyperlink in a message. I thought it should be done by regular expressions and then surrounded with a a-tag. But how to do a regular expression that extracts a link from a message?

Here's my incomplete attempt:

var str = ' Disappointing Usability http://t.co/wkTFYhQq';
 var pattern = /http:///w{1,100}/i
 var str2 =  pattern.exec(str);
 alert(str2); 
Community
  • 1
  • 1
marko
  • 10,684
  • 17
  • 71
  • 92

2 Answers2

3

Use match with this regex, that should get you an array with all links in a string:

/(?:https?|ftp|www)[^\s]+/g
elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

Your pattern should capture the URL in a group:

var pattern = /(...)/;
var output = input.replace(pattern, '<a href="$1">$1</a>');

There are heaps of URL patterns available, depending on how inclusive you want to be.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222