Format URLs in string to HTML Links in C#

/ Published in: C#
Save to your folder(s)

Will return a string that has any matched URLs wrapped in `<a>` tags.

Example: `"This is a link to . Please visit !"`

Becomes: `"This is a link to <a href=''></a> . Please visit!"`

Note: Opens links in new window.

Credit for regex:
[Faraz Shah Khan]( "Credit")

Copy this code and paste it in your HTML
  1. public static string FormatUrls(string input) {
  2. string output = input;
  3. Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
  5. MatchCollection mactches = regx.Matches(output);
  7. foreach (Match match in mactches) {
  8. output = output.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>");
  9. }
  10. return output;
  11. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.