识别http链接并创建锚标记 [英] Recognizing http links and creating anchor tags

查看:107
本文介绍了识别http链接并创建锚标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to parse some string and it has some http links embedded in it. I'd like to dynamically create anchor tags within this string using jquery then display them on the front end so the user can click them.

有没有办法做到这一点?

Is there a way to do this?

谢谢!

推荐答案

您可以这样做:

$(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);
});

工作示例

这篇关于识别http链接并创建锚标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆