Skip to content

Instantly share code, notes, and snippets.

@hallojoe
Last active June 23, 2016 19:28
Show Gist options
  • Save hallojoe/213a34c0d9685a988ba39c29d9151910 to your computer and use it in GitHub Desktop.
Save hallojoe/213a34c0d9685a988ba39c29d9151910 to your computer and use it in GitHub Desktop.
Generate slug from string - See https://en.wikipedia.org/wiki/Semantic_URL#Slug
using System.Text.RegularExpressions;
namespace App.Extensions
{
/// <summary>
/// Generate slug from string
/// </summary>
public static class SlugExtensions
{
/// <summary>
/// Identifies a string in human readable resamblance of words separated by dash "-"
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string ToSlug(this string s)
{
// remove accents and convert to lowercase
s = s.WithoutAccent().ToLower();
// replace non alphanumeric (A to Z or 0 to 9) characters with whitespace
s = Regex.Replace(s, @"[^a-z0-9\s-]", "");
// convert multiple whitespace to single whitespace
s = Regex.Replace(s, @"\s+", " ").Trim();
// truncate string if 45 chars+ and trim
s = s.Substring(0, s.Length <= 45 ? s.Length : 45).Trim();
// replace whitespace with dash
s = Regex.Replace(s, @"\s", "-");
// yeah!
return s;
}
/// <summary>
/// Get string without accent - good for getting any encoded string as whitespace and A-Z and 0-9 string
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string WithoutAccent(this string s)
{
// read bytes with cyrrelic encoding into byte array - no accents
byte[] b = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(s);
// return ASCII encoded text from "Cyrillic" byte array
return System.Text.Encoding.ASCII.GetString(b);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment