识别http链接并创建锚标签

我正在尝试解析一些字符串,并且它中嵌入了一些http链接。 我想使用jquery在此字符串中动态创建锚标记,然后在前端显示它们,以便用户可以单击它们。

有没有办法做到这一点?

谢谢!

你可以这样做:

$(function(){ //get the string var str = $("#text").html(); //create good link matching regexp var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/g // https://stackoverflow.com/questions/5919760/recognizing-http-links-and-creating-anchor-tags/$1 is the found URL in the text // str.replace replaces the found url with https://stackoverflow.com/questions/5919760/recognizing-http-links-and-creating-anchor-tags/THE URL var replaced_text = str.replace(regex, "https://stackoverflow.com/questions/5919760/recognizing-http-links-and-creating-anchor-tags/$1") //replace the contents $("#text").html(replaced_text); }); 

工作实例

@cfarm,你可以抓住url并构建自己的html。

解析字符串并开始制作url并在你的Html中保留占位符,使用

http://api.jquery.com/html/

要么

http://api.jquery.com/append/