Skip to content

Instantly share code, notes, and snippets.

@caferrari
Last active August 29, 2015 14:15
Show Gist options
  • Save caferrari/93f7d08200e13de28e08 to your computer and use it in GitHub Desktop.
Save caferrari/93f7d08200e13de28e08 to your computer and use it in GitHub Desktop.
C# string.ToSlug() Extension Method
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