Guest User

Untitled

a guest
Sep 21st, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. public static class StringExtensions
  2. {
  3. private const string SINGLE_SPACE = " ";
  4. private const string HYPHEN = "-";
  5. private const string CODE_PAGE_NAME = "Cyrillic";
  6.  
  7. private const string INVALID_CHARS_PATTERN = @"[^a-z0-9\s-]";
  8. private const string MULTIPLE_SPACES_PATTERN = @"\s+";
  9. private const string SINGLE_SPACE_PATTERN = @"\s";
  10.  
  11.  
  12. public static string ToSlug(this string phrase, int maxlength = 0)
  13. {
  14. return phrase
  15. .RemoveAccent()
  16. .ToLower()
  17. .RemoveInvalidChars()
  18. .ReduceSpaces()
  19. .CutAndTrim(maxlength)
  20. .Hyphenate();
  21. }
  22.  
  23. public static string RemoveInvalidChars(this string phrase)
  24. {
  25. return Regex.Replace(phrase, INVALID_CHARS_PATTERN, string.Empty);
  26. }
  27.  
  28. public static string ReduceSpaces(this string phrase)
  29. {
  30. return Regex.Replace(phrase, MULTIPLE_SPACES_PATTERN, SINGLE_SPACE).Trim();
  31. }
  32.  
  33. public static string CutAndTrim(this string phrase, int maxLength = 0)
  34. {
  35. if (maxLength > 0)
  36. return phrase.Substring(0, phrase.Length <= maxLength ? phrase.Length : maxLength).Trim();
  37. else
  38. return phrase.Trim();
  39. }
  40.  
  41. public static string Hyphenate(this string phrase)
  42. {
  43. return Regex.Replace(phrase, SINGLE_SPACE_PATTERN, HYPHEN);
  44. }
  45. public static string RemoveAccent(this string phrase)
  46. {
  47. byte[] bytes = System.Text.Encoding.GetEncoding(CODE_PAGE_NAME).GetBytes(phrase);
  48. return System.Text.Encoding.ASCII.GetString(bytes);
  49. }
  50. }
Add Comment
Please, Sign In to add comment