Recognize http links and create anchor tags

I am trying to parse some string and it has some http links in it. I would like to dynamically create anchor tags on this line using jquery and then display them at the front end so the user can click them.

Is there any way to do this?

Thanks!

+2
source share
2 answers

You can do it as follows:

$(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

+7
source

@cfarm, you can grab the urls and build your own html code.

parse the string and start creating urls and save space in your html, use

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

or

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

0
source

Source: https://habr.com/ru/post/1385834/


All Articles