Skip to content

Instantly share code, notes, and snippets.

@dehghani-mehdi
Created October 1, 2018 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dehghani-mehdi/6717bb54304e2e188766ff31da7fa740 to your computer and use it in GitHub Desktop.
Save dehghani-mehdi/6717bb54304e2e188766ff31da7fa740 to your computer and use it in GitHub Desktop.
Generate clean url slug in C#
public string Slugify(string s)
{
if (string.IsNullOrWhiteSpace(s)) return "";
// removing extra spaces and keeping just one
s = string.Join(" ", Regex.Split(s, @"\s+")).ToLower();
var specialPhases = new Dictionary<string, string>
{
{"c#","c-sharp"},
{"f#","f-sharp"},
{"_","-"},
};
foreach (var item in specialPhases) s = s.Replace(item.Key, item.Value);
var matches = Regex.Matches(s, "[\\w]+");
var words = new List<string>();
foreach (Match m in matches) words.Add(m.Value);
return string.Join("-", words);
}
// Usage
var slug = Slugify("I love C# ~!@#$%^&*()_+=-|\\/';:}{[]"); // i-love-c-sharp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment