-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathkebab_case.rs
51 lines (43 loc) · 1.49 KB
/
kebab_case.rs
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
//! Converts `String` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
//! This method is like `find` except that it iterates over elements of
//! `collection` from right to left.
//!
//! Example
//! ```
//! use lodash_rust::kebab_case;
//!
//! let value = String::from("Foo Bar");
//! let res = kebab_case::new(&value);
//! println!("{res}") // "foo-bar"
//! ```
extern crate regex;
pub fn new(s: &str) -> String {
let re = regex::Regex::new("[^a-zA-Z0-9]+").unwrap();
let result = re.replace_all(s, " ");
let result = result.trim();
let hyphen = "-";
let result_string = re.replace_all(result, hyphen);
// check if string contains "-"
let re2 = regex::Regex::new(format!("[{hyphen}]+").as_str()).unwrap();
let contains_hyphen = re2.is_match(result_string.as_ref());
let mut build_result_string = String::new();
if !contains_hyphen {
let mut tmp = [0u8; 4];
// convert to char
let characters: Vec<char> = result_string.chars().collect();
for letter in characters {
if letter.is_uppercase() {
build_result_string.push_str(hyphen);
}
build_result_string.push_str(letter.encode_utf8(&mut tmp));
}
return build_result_string.to_lowercase();
}
result_string.to_string().to_lowercase()
}
#[test]
fn test_new() {
assert_eq!(new("Foo Bar"), "foo-bar");
assert_eq!(new("fooBar"), "foo-bar");
assert_eq!(new("__FOO_BAR__"), "foo-bar");
}