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");
- }
This function accept url in text format and by using regular expression it checks if that is correct url format or not if yes then it convert to HTML link otherwise return plain text.
In my aspx page I am creating a div like:
- <div id="UrlDiv" runat ="server" >
- </div>
After that passing url to above function in page load and text the result.
Case 1
- string Url = "www.google.com";
-
- UrlDiv.InnerHtml =ConvertTextUrlToLink(Url);
Output
www.google.com // converted to link
Case 2
- string Url = "google.com";
- UrlDiv.InnerHtml =ConvertTextUrlToLink(Url);
Output
google.com // plain text
Above is small but very interesting code it may be useful for all.