1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#![crate_type = "lib"] #![crate_name = "spaceslugs"] extern crate regex; use regex::Regex; pub struct Slug; impl Slug { pub fn from(string: String) -> String { let re_replace_non_ascii = Regex::new(r"[^\x00-\x7F]").unwrap(); let re_replace_single_quotes = Regex::new(r"[']+").unwrap(); let re_replace_non_char = Regex::new(r"\W+").unwrap(); let re_replace_spaces = Regex::new(r"[ ]+").unwrap(); let mut result = string.to_string(); result = re_replace_non_ascii.replace_all(&result[..], ""); result = re_replace_single_quotes.replace_all(&result[..], ""); result = re_replace_non_char.replace_all(&result[..], " "); result = result.trim().to_string(); result = re_replace_spaces.replace_all(&result[..], "-"); result.to_lowercase() } } #[test] fn replace_character_case() { assert_eq!("test".to_string(), Slug::from("TEST".to_string())); } #[test] fn replace_single_quotes() { assert_eq!("".to_string(), Slug::from("'".to_string())); } #[test] fn replace_non_char() { assert_eq!("".to_string(), Slug::from("!".to_string())); } #[test] fn replace_spaces() { assert_eq!("1-2".to_string(), Slug::from("1 2".to_string())); } #[test] fn it_works() { let title = "This: just 1 great test title, y'know?...".to_string(); assert_eq!("this-just-1-great-test-title-yknow".to_string(), Slug::from(title)); }