Search code examples
c#slug

URL Slugify algorithm in C#?


So I have searched and browsed through the slug tag on SO and only found two compelling solution:

Which are but partial solution to the problem. I could manually code this up myself but I'm surprised that there isn't already a solution out there yet.

So, is there a slugify alrogithm implementation in C# and/or .NET that properly address latin characters, unicode and various other language issues properly?


Solution

  • http://predicatet.blogspot.com/2009/04/improved-c-slug-generator-or-how-to.html

    public static string GenerateSlug(this string phrase) 
    { 
        string str = phrase.RemoveAccent().ToLower(); 
        // invalid chars           
        str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); 
        // convert multiple spaces into one space   
        str = Regex.Replace(str, @"\s+", " ").Trim(); 
        // cut and trim 
        str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim();   
        str = Regex.Replace(str, @"\s", "-"); // hyphens   
        return str; 
    } 
    
    public static string RemoveAccent(this string txt) 
    { 
        byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt); 
        return System.Text.Encoding.ASCII.GetString(bytes); 
    }