Recognizing http links and creating anchor tags

女生的网名这么多〃 提交于 2019-12-11 03:24:36

问题


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?

Thanks!


回答1:


You can do it like 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);
});

working example




回答2:


@cfarm , you can grab the urls and construct html of your own.

parse the string and start making the urls and keep a place holder in your Html , use

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

or

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



来源:https://stackoverflow.com/questions/5919760/recognizing-http-links-and-creating-anchor-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!