Turn URLs into hyperlinks in ASP.NET

Jun 6, 2006

Today, I needed a function that would look through some text input and check for any URLs and the URLs should then be turned into hyperlinks. In other words, I had to turn this www.someurl.com into <a href="http://www.someurl.com" target="_blank">www.someurl.com</a>. It should also be able to handle URLs that starts with http:\\ and not just www.

I needed this functionality in a forum/comment application and it had to do the conversion at runtime. I wrote a simple regular expression for the URLs starting with http:\\ and another for URL's starting with www. These to regular expression are then combined into one method that takes a body of text and replaces all URLs with a proper hyperlink.

Here's what I came up with in C#:

private static string ResolveLinks(string body)
{
   body = System.Text.RegularExpressions.Regex.Replace(body, "(http://[^ ]*[a-zA-Z0-9])", "<a href=\"$1\" target=\"_blank\">$1</a>");
   body = System.Text.RegularExpressions.Regex.Replace(body, "(www.[^ ]*[a-zA-Z0-9])", "<a href=\"http://$1\" target=\"_blank\">$1</a>");
   return body;
}

All the comments in this application passes through this method, and all typed URLs get transformed.

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (2) -

 dede
dede
6/8/2006 11:37:04 AM #

I have similar model but still not prefect.
blogs.netindonesia.net/.../9952.aspx

 Ihar Bury
Ihar Bury
7/25/2006 4:32:55 PM #

What about http://orlangur-8eyed.livejournal.com/ ? Wink

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.