Last active
February 25, 2023 18:03
-
-
Save jeremy-farrance/7b22568909facc448cf0a09dd459e482 to your computer and use it in GitHub Desktop.
ToSlug, Generate URL slug from a name, title, etc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?