Last active
June 23, 2016 19:28
-
-
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
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
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