Transform url to links with C#

December, 14th 2011 | .NET

In some cases, such as the comments of a social newtork, you may want to turn urls entered by a user into clickable links.
In Igloo we had the need to create a function that would allow us to achieve this result and we want to share it.

public static string Url2Link (string text)
{
     Regex regex = new Regex (@ "(http (s?): \ / \ / ([\ W.] + \ /?) \ S *)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
     return Regex.Replace (text, "<a href=\"$1\" target=\"_blank\"> $ 1 </ a>");
}