String extension method for generating URI slugs.
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace Extensions;
public static partial class StringExtensions
{
#region - ToSlug -
public static string ToSlug(this string self, int maxLength = 1024)
{
if (string.IsNullOrEmpty(self))
{
return self;
}
var str = RemoveAccent(self).ToLower(CultureInfo.InvariantCulture);
str = InvalidCharsRegEx().Replace(str, ""); // invalid chars
str = MultipleWhitespacesRegEx().Replace(str, " ").Trim(); // convert multiple spaces into one space
str = str.Substring(0, str.Length <= maxLength ? str.Length : maxLength).Trim(); // cut and trim it
str = WhitespaceRegEx().Replace(str, "-"); // hyphens
str = MultipleHyphensRegEx().Replace(str, "-");
return str.Trim('-'); // trim leading and trailing hyphens
}
private static string RemoveAccent(string value)
{
var bytes = Encoding.GetEncoding("Cyrillic").GetBytes(value);
return Encoding.ASCII.GetString(bytes);
}
[GeneratedRegex("[^a-z0-9\\s-]")]
private static partial Regex InvalidCharsRegEx();
[GeneratedRegex("\\s+")]
private static partial Regex MultipleWhitespacesRegEx();
[GeneratedRegex("\\-+")]
private static partial Regex MultipleHyphensRegEx();
[GeneratedRegex("\\s")]
private static partial Regex WhitespaceRegEx();
#endregion
}