Extract and add URL link in line

Possible duplicate:
How to replace simple links to links?

I have some lines in which there are links. For instance:

var str = "I really love this site: http://www.stackoverflow.com"

and I need to add a link tag to it, so str will be:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>

I suppose some regular expression will be involved, but I cannot get it to work for me with match (). Any other ideas

+3
source share
3 answers

This is easy:

str.replace( /(http:\/\/[^\s]+)/gi , '<a href="$1">$1</a>' )

Conclusion:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>
+9
source
function replaceURL(val) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return val.replace(exp,"<a href='$1'>$1</a>"); 
}
+3
source

. -

RegExp exp = new RegExp('(.*)(http://[^ ])(.*)', 'g'); // matches URLs
string = string.replace(exp, $1 + '<a href=\"' + $2 + '\">' + $2 '</a>' + $3);

I have not tested it yet, so I need some clarification.

0
source

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


All Articles