Creating a slug from a string in C#

Oct 23, 2023 /
# C#

Turning strings into a slug is common use case in applications.

For example, lets say you have a string that represents a blog posts title. For SEO purposes, you will want to take that name and turn it into a url friendly version.

Here is a simple c# extension method to help you do that.

public static string Slugify(this string input)
{
    string str = input.RemoveDiacritics().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();
    // hyphens
    str = Regex.Replace(str, @"\s", "-");
    return str;
}

// example usage
var str = "Hello world";
var slug = str.Slugify();
// slug = "hello-world";

The RemoveDiacritics method from above

private static string RemoveDiacritics(this string str)
{
    var normalizedString = str.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder(capacity: normalizedString.Length);

    for (int i = 0; i < normalizedString.Length; i++)
    {
        char c = normalizedString[i];
        var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder
        .ToString()
        .Normalize(NormalizationForm.FormC);
}

Early Access

Dotnet Engine will be launching in early access soon. Signup with your email now to get notified when early access starts and a special launch price.