Created
January 15, 2014 13:55
-
-
Save joancaron/8436664 to your computer and use it in GitHub Desktop.
How to generate clean url slug in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string ToUrlSlug(string value){ | |
//First to lower case | |
value = value.ToLowerInvariant(); | |
//Remove all accents | |
var bytes = Encoding.GetEncoding("Cyrillic").GetBytes(value); | |
value = Encoding.ASCII.GetString(bytes); | |
//Replace spaces | |
value = Regex.Replace(value, @"\s", "-", RegexOptions.Compiled); | |
//Remove invalid chars | |
value = Regex.Replace(value, @"[^\w\s\p{Pd}]", "",RegexOptions.Compiled); | |
//Trim dashes from end | |
value = value.Trim('-', '_'); | |
//Replace double occurences of - or \_ | |
value = Regex.Replace(value, @"([-_]){2,}", "$1", RegexOptions.Compiled); | |
return value ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment