Turn URLs into hyperlinks in ASP.NET

by Mads Kristensen 7. June 2006 02:51

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.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments

6/8/2006 8:37:04 PM #

 dede

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

dede |

7/26/2006 1:32:55 AM #

 Ihar Bury

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

Ihar Bury |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008