using System.Text; using System.Text.RegularExpressions; public static class StringExtensions { public static string ToShortDescription(this string ls, int length) { if (!string.IsNullOrEmpty(ls.Trim())) { ls = ls.Trim().StripSpecialCharacters(); if (ls.Length > length) { ls = ls.Substring(0, length - 3); //-3 for dots ls = ls.Remove(ls.LastIndexOf(" "), (ls.Length - ls.LastIndexOf(" "))); ls += "..."; } return ls; } return string.Empty; } public static string StripSpecialCharacters(this string s) { if (string.IsNullOrEmpty(s)) return string.Empty; Regex r = new Regex(@"\s+");//remove all whitespace s = r.Replace(s, " "); // to a single space MatchCollection mc = Regex.Matches(s, @"[A-Za-z0-9]|\s+", RegexOptions.IgnoreCase); s = string.Empty; foreach (Match m in mc) { s += m.ToString(); } return s; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter