开发者

Extract and add link to URLs in string [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

How to replace plain URLs with links?

I have several strings that have links in them. For ins开发者_JAVA技巧tance:

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


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>


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>"); 
}


I can think of a quick and dirty Regular Expression based solution. Something on the lines of

RegExp exp = new RegExp('(.*)(http://[^ ])(.*)', 'g'); // matches URLs
string = string.replace(exp, $1 + '<a href=\"' + $2 + '\">' + $2 '</a>' + $3);

I haven't tested it yet though, so needs some refining.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜