Recognizing http links and creating anchor tags

2019-07-15 13:31发布

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!

2条回答
Juvenile、少年°
2楼-- · 2019-07-15 14:02

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

查看更多
够拽才男人
3楼-- · 2019-07-15 14:12

@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/

查看更多
登录 后发表回答