Skip to content

Instantly share code, notes, and snippets.

@jeremy-farrance
Last active February 25, 2023 18:03
Show Gist options
  • Save jeremy-farrance/7b22568909facc448cf0a09dd459e482 to your computer and use it in GitHub Desktop.
Save jeremy-farrance/7b22568909facc448cf0a09dd459e482 to your computer and use it in GitHub Desktop.
ToSlug, Generate URL slug from a name, title, etc.
@functions {
// Turn any text or title in to a URL Slug
// original = https://stackoverflow.com/questions/2920744/url-slugify-algorithm-in-c
// .ToSlug("My Title=Heading - &*(-) end-") >> "my-titleheading-end"
public string ToSlug(string phrase)
{
byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(phrase);
string str = System.Text.Encoding.ASCII.GetString(bytes);
str = str.ToLower();
// invalid chars to hyphens
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();
str = Regex.Replace(str, @"\s", "-"); // hyphens
// convert multiple hyphens into one hyphen (JRF)
str = Regex.Replace(str, "-+", "-");
return str.Trim('-'); // leading/trailing hyphens (JRF)
}
}
@jeremy-farrance
Copy link
Author

Improvements?

https://github.com/Accuraty/FASS-WP-Authenticator/blob/main/fass-external-login/js/tools.js
^^^
Converting accents seems like a good addition.
Maybe also compare RegExs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment