jquery - 识别http链接并创建 anchor 标记

标签 jquery regex anchor

我正在尝试解析一些字符串,它嵌入了一些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);
});

working example

关于jquery - 识别http链接并创建 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5919760/

相关文章:

asp.net-mvc-3 - .net MVC 3.0 带进度条的文件上传

regex - Apache .htaccess重写规则以删除.php文件扩展名

winforms - 如何根据分辨率调整控件大小?

javascript - 提取外部 javascript 查询字符串/ anchor 值 : file. js#foo=bar

javascript - 使用 jquery 将 anchor 添加到链接

jquery - "only-visible-child"元素?

javascript - Twilio Conversation 挂断主叫端的邀请

javascript - 获取 AngularJs 中的特定元素

c# - 这个 "password"的正则表达式是什么?

javascript - 棱镜 : Match language types not starting with dot or : character