Skip to main content

C# extension methods that transforms a string to be URL friendly (slug).

using System;
using System.Text;
using System.Text.RegularExpressions;

public static class StringExtensions
{
    private static readonly string urlPattern = "[^a-zA-Z0-9-.]";

    public static string Slugify(this string url)
    {
        var friendlyUrl = Regex.Replace(url, @"\s", "-").ToLower();
        friendlyUrl = Regex.Replace(friendlyUrl, urlPattern, string.Empty);

        return friendlyUrl;
    }

    public static string Slugify(this string url, string pattern, string replace = "")
    {
        var friendlyUrl = Regex.Replace(url, @"\s", "-").ToLower();
        friendlyUrl = Regex.Replace(friendlyUrl, pattern, replace);

        return friendlyUrl;
    }
}