Reputation: 473
i defined ToHtml() extension for string class and convert break to <br/>
.
how can detect hyper link and convert to <a>
element?
public static class StringExtension
{
public static string ToHtml(this string item)
{
//\r\n windows
//\n unix
//\r mac os
return item.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>");
}
}
c#, asp.net
Upvotes: 3
Views: 11061
Reputation: 37566
By using:
string strContent = YourText;
Regex urlregex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)",
RegexOptions.IgnoreCase| RegexOptions.Compiled);
strContent = urlregex.Replace(strContent,
"<a href=\"$1\" target=\"_blank\">$1</a>");
Upvotes: 1
Reputation: 878
You could use a regular expression here to identify where the hyperlink begins and ends (possibly based on the length of the match) Then add in your anchor tags before and after.
Upvotes: 1
Reputation: 4701
see this one, uses regex
private string ConvertUrlsToLinks(string msg) {
string regex = @"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
return r.Replace(msg, "<a href=\"$1\" title=\"Click to open in a new window or tab\" target=\"_blank\">$1</a>").Replace("href=\"www", "href=\"http://www");
}
Upvotes: 5