Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class StringExtensions
- {
- private const string SINGLE_SPACE = " ";
- private const string HYPHEN = "-";
- private const string CODE_PAGE_NAME = "Cyrillic";
- private const string INVALID_CHARS_PATTERN = @"[^a-z0-9\s-]";
- private const string MULTIPLE_SPACES_PATTERN = @"\s+";
- private const string SINGLE_SPACE_PATTERN = @"\s";
- public static string ToSlug(this string phrase, int maxlength = 0)
- {
- return phrase
- .RemoveAccent()
- .ToLower()
- .RemoveInvalidChars()
- .ReduceSpaces()
- .CutAndTrim(maxlength)
- .Hyphenate();
- }
- public static string RemoveInvalidChars(this string phrase)
- {
- return Regex.Replace(phrase, INVALID_CHARS_PATTERN, string.Empty);
- }
- public static string ReduceSpaces(this string phrase)
- {
- return Regex.Replace(phrase, MULTIPLE_SPACES_PATTERN, SINGLE_SPACE).Trim();
- }
- public static string CutAndTrim(this string phrase, int maxLength = 0)
- {
- if (maxLength > 0)
- return phrase.Substring(0, phrase.Length <= maxLength ? phrase.Length : maxLength).Trim();
- else
- return phrase.Trim();
- }
- public static string Hyphenate(this string phrase)
- {
- return Regex.Replace(phrase, SINGLE_SPACE_PATTERN, HYPHEN);
- }
- public static string RemoveAccent(this string phrase)
- {
- byte[] bytes = System.Text.Encoding.GetEncoding(CODE_PAGE_NAME).GetBytes(phrase);
- return System.Text.Encoding.ASCII.GetString(bytes);
- }
- }
Add Comment
Please, Sign In to add comment