开发者

What is the easiest way to replace a url string (in a text) with an anchor tag?

开发者 https://www.devze.com 2023-04-02 21:14 出处:网络
I have text: I love Stackoverflow so much, so please visist http://stackoverflow.com How can I transform it to:

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 hrefto 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

0

精彩评论

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