Last active
August 29, 2015 14:15
-
-
Save caferrari/93f7d08200e13de28e08 to your computer and use it in GitHub Desktop.
C# string.ToSlug() Extension Method
This file contains hidden or 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 ToSlug(this string source, short limit) | |
{ | |
// Is the source null? | |
if (null == source) { | |
return ""; | |
} | |
// Remove accents | |
var bytes = Encoding.GetEncoding("Cyrillic").GetBytes(source); | |
var value = Encoding.ASCII.GetString(bytes); | |
// Converts "GooglePlus" to "-google-plus" | |
value = Regex.Replace(value, @"([A-Z])", "-$1").ToLowerInvariant(); | |
// Remove invalid characters | |
value = Regex.Replace(value, @"[^a-z0-9]+", "-"); | |
// Remove hyphens | |
value = value.Trim('-'); | |
// Check the limit and truncate the string | |
if (limit > 0 && value.Length > limit) | |
{ | |
value = value.Substring(0, limit).Trim('-'); | |
} | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment