Skip to content

Instantly share code, notes, and snippets.

@oal
Created July 28, 2015 10:51
Show Gist options
  • Save oal/f079d573a760a0f67c23 to your computer and use it in GitHub Desktop.
Save oal/f079d573a760a0f67c23 to your computer and use it in GitHub Desktop.
Read http://olav.it/experiment/rust-slugify/ before using this.
fn slugify(text: &str) -> String {
// Create a mutable string to add slug characters to
let mut slug = String::with_capacity(text.len());
for c in text.chars() {
// Check if the current character is a special character, and needs to be replaced
let replacement = match c {
' ' => Some("-"),
// Scandinavian
'Æ' | 'æ' | 'Ä' | 'ä' => Some("ae"),
'Ø' | 'ø' | 'Ö' | 'ö' => Some("oe"),
'Å' | 'å' => Some("aa"),
// German
'ẞ' | 'ß' => Some("ss"),
'Ü' | 'ü' => Some("u"),
_ => None,
};
// Replace if needed. Then check next character.
if let Some(replacement) = replacement {
slug.push_str(replacement);
continue
}
// No replacements needed, just lowercase the character and add it.
match c.to_lowercase().last().unwrap() {
a @ 'a'...'z' | a @ '0'...'9' => slug.push(a),
_ => (),
}
};
// Shrink in case we didn't fill the allocated string.
slug.shrink_to_fit();
slug
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment