我正在尝试解析一些字符串,它嵌入了一些http链接。我想使用 jquery 在此字符串中动态创建 anchor 标记,然后将它们显示在前端,以便用户可以单击它们。
有办法做到这一点吗?
谢谢!
最佳答案
你可以这样做:
$(function(){
//get the string
var str = $("#text").html();
//create good link matching regexp
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/g
// $1 is the found URL in the text
// str.replace replaces the found url with <a href='THE URL'>THE URL</a>
var replaced_text = str.replace(regex, "<a href='$1'>$1</a>")
//replace the contents
$("#text").html(replaced_text);
});
关于jquery - 识别http链接并创建 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5919760/