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 into <a href="" target="_blank"></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.


Comments are closed