用锚标记替换url字符串(在文本中)的最简单方法是什么?

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

本文关键字:最简单 方法 是什么 文本 替换 url 字符串      更新时间:2023-09-26

我有文字:

I love Stackoverflow so much, so please visist http://stackoverflow.com

如何将其转换为:

I love Stackoverflow so much, so please visist <a href='http://stackoverflow.com'>http://stackoverflow.com</a>

在javascript中最简单的方式?

请注意,文本中的url可以没有http://和没有wwww,但我希望属性href至少包含http://。还要考虑到一些链接是https://

试试这个-

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

工作演示- http://jsfiddle.net/5cKhn/

取自RegEx Buddy中的RegEx库