einstein
einstein

Reputation: 13850

What is the easiest way to replace a url string (in a text) with an anchor tag?

I have text:

I love Stackoverflow so much, so please visist http://stackoverflow.com

How can I transform it to:

I love Stackoverflow so much, so please visist <a href='http://stackoverflow.com'>http://stackoverflow.com</a>

in the easiest way in javascript?

Note that the url in text could be without http:// and without wwww, but I want the attribute hrefto contain at least http://. Also take in consideration that some links are https://

Upvotes: 1

Views: 4840

Answers (1)

ipr101
ipr101

Reputation: 24236

Try this -

var text = 'I love Stackoverflow so much, so please visist http://stackoverflow.com';
result = text.replace(/(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z09+&@#\/%=~_|])/img, '<a href="$1">$1</a>');
alert(result);

Working demo - http://jsfiddle.net/5cKhn/

RegEx taken from RegEx library within RegEx Buddy

Upvotes: 3

Related Questions