I have text:
I love Stackoverflow so much, so please visist http://stackoverflow.com
How can I transform it to:
I love Stackoverflow so much, so please visist <a href='http://stackoverflow.com'>http://stackoverflow.com</a>
in the easiest way 开发者_高级运维in javascript?
Note that the url in text could be without http://
and without wwww
, but I want the attribute href
to contain at least http://
. Also take in consideration that some links are https://
Try this -
var text = 'I love Stackoverflow so much, so please visist http://stackoverflow.com';
result = text.replace(/(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z09+&@#\/%=~_|])/img, '<a href="$1">$1</a>');
alert(result);
Working demo - http://jsfiddle.net/5cKhn/
RegEx taken from RegEx library within RegEx Buddy
精彩评论