Last project I got a small but interesting issue in which I have to convert plain text url to html link and also check if url is in correct format then only I need to convert it to link otherwise as it is displayed in my webpage. I have create following C# function for doing that.
- private string ConvertTextUrlToLink(string url)
- {
- string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.
- [a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
- Regex r = new Regex(regex, RegexOptions.IgnoreCase);
- return r.Replace(url, "a href=\"$1\" title=\"Click here to open in a new window or tab\"
- target=\"_blank\">$1</a>").Replace("href=\"www", "href=\"http://www");
- }
In my aspx page I am creating a div like:
- <div id="UrlDiv" runat ="server" >
- </div>
Case 1
- string Url = "www.google.com";
- UrlDiv.InnerHtml =ConvertTextUrlToLink(Url);
www.google.com // converted to link
Case 2
- string Url = "google.com";
- UrlDiv.InnerHtml =ConvertTextUrlToLink(Url);
google.com // plain text
Above is small but very interesting code it may be useful for all.

Join the conversation! Your thoughts help the community grow.