Created
December 31, 2016 18:13
-
-
Save hclewk/4903b3e72d321512186c2be9ccaf2c7c to your computer and use it in GitHub Desktop.
Make Slug - Makes a url-friendly "slug" Input: "St. Patrick's Day: Awësöme tö-dö's" Output: "st-patricks-day-awesome-to-dos"
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
//Input: "St. Patrick's Day: Awësöme tö-dö's" | |
//Output: "st-patricks-day-awesome-to-dos" | |
public static string MakeSlug(string url) | |
{ | |
url = RemoveDiacritics(url.ToLowerInvariant()); | |
url = Regex.Replace(url, @"[^a-z0-9\-\s]", ""); | |
url = Regex.Replace(url, @"\s+", "-"); | |
url = Regex.Replace(url, @"\-+", "-").Trim('-'); | |
return url; | |
} | |
/// See: http://www.siao2.com/2007/05/14/2629747.aspx | |
private static string RemoveDiacritics(string stIn) | |
{ | |
string stFormD = stIn.Normalize(NormalizationForm.FormD); | |
StringBuilder sb = new StringBuilder(); | |
for (int ich = 0; ich < stFormD.Length; ich++) | |
{ | |
System.Globalization.UnicodeCategory uc = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]); | |
if (uc != System.Globalization.UnicodeCategory.NonSpacingMark) | |
{ | |
sb.Append(stFormD[ich]); | |
} | |
} | |
return (sb.ToString().Normalize(NormalizationForm.FormC)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment