识别http链接并创建锚标签

loc*_*boy 2 regex anchor jquery

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

有没有办法做到这一点?

谢谢!

Ten*_*eff 7

你可以这样做:

$(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);
});
Run Code Online (Sandbox Code Playgroud)

工作实例