Skip to content

Instantly share code, notes, and snippets.

@allrameest
Last active August 29, 2015 14:08
Show Gist options
  • Save allrameest/b8abc7605f6333ec4f13 to your computer and use it in GitHub Desktop.
Save allrameest/b8abc7605f6333ec4f13 to your computer and use it in GitHub Desktop.
public static class UrlSlugGenerator
{
private static readonly IDictionary<string, string> UrlReplacementMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{"&", "-"},
{" ", "-"},
{"/", "-"},
{"+", "-"},
};
private static readonly Regex UrlReplacementRegex = new Regex(string.Format("([{0}])", string.Concat(UrlReplacementMap.Keys.Select(Regex.Escape))), RegexOptions.Compiled);
private static readonly Regex InvalidCharRegex = new Regex(@"[^\w-]", RegexOptions.Compiled);
private static readonly Regex MultipleDashesRegex = new Regex("-{2,}", RegexOptions.Compiled);
public static string Sluggify(string value)
{
if (value == null) throw new ArgumentNullException("value");
var result = UrlReplacementRegex.Replace(value, m => UrlReplacementMap[m.Groups[1].ToString()]);
result = RemoveDiacritics(result);
result = InvalidCharRegex.Replace(result, "");
result = MultipleDashesRegex.Replace(result, "-");
result = result.Trim('-');
return result.ToLower();
}
private static string RemoveDiacritics(string s)
{
var bytes = Encoding.GetEncoding("Cyrillic").GetBytes(s);
return Encoding.ASCII.GetString(bytes);
}
}
[TestFixture]
public class UrlSlugGeneratorTests
{
[TestCase("åäö æł", "aao-al")]
[TestCase("a - b", "a-b")]
[TestCase("Força Barça", "forca-barca")]
[TestCase("ëêéèñûüúùóø", "eeeenuuuuoo")]
[TestCase("foo ", "foo")]
[TestCase("a,b;c", "abc")]
[TestCase("ąćęłńóśźżőűğıİş", "acelnoszzougiis")]
[TestCase("ăâîşţ", "aaist")]
[TestCase("ß", "")]
[TestCase("d.a.d.", "dad")]
[TestCase("Øyvind", "oyvind")]
public void Generates_expected_slug(string input, string expected)
{
var slug = UrlSlugGenerator.Sluggify(input);
slug.Should().Be.EqualTo(expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment