Recognizing http links and creating anchor tags

2019-07-15 13:26发布

问题:

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/