lodash_rust/
kebab_case.rs

1//! Converts `String` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
2//! This method is like `find` except that it iterates over elements of
3//! `collection` from right to left.
4//!
5//! Example
6//! ```
7//! use lodash_rust::kebab_case;
8//! 
9//! fn main() {
10//!  let value = String::from("Foo Bar")
11//!  let res = kebab_case::new(value);
12//!  println!("{res}") // "foo-bar"
13//! }
14//! ```
15//!
16
17extern crate regex;
18
19pub fn new(s: &str) -> String {
20    let re = regex::Regex::new("[^a-zA-Z0-9]+").unwrap();
21    let result = re.replace_all(s, " ");
22    let result = result.trim();
23    let hyphen = "-";
24    let result_string = re.replace_all(result, hyphen);
25
26    // check if string contains "-"
27    let re2 = regex::Regex::new(format!("[{hyphen}]+").as_str()).unwrap();
28    let contains_hyphen = re2.is_match(result_string.as_ref());
29
30    let mut build_result_string = String::new();
31
32    if !contains_hyphen {
33        let mut tmp = [0u8; 4];
34        // convert to char
35        let characters: Vec<char> = result_string.chars().collect();
36        for letter in characters {
37            if letter.is_uppercase() {
38                build_result_string.push_str(hyphen);
39            }
40            build_result_string.push_str(letter.encode_utf8(&mut tmp));
41        }
42
43        return build_result_string.to_lowercase();
44    }
45
46    return result_string.to_string().to_lowercase();
47}
48
49#[test]
50fn test_new() {
51    assert_eq!(new("Foo Bar"), "foo-bar");
52    assert_eq!(new("fooBar"), "foo-bar");
53    assert_eq!(new("__FOO_BAR__"), "foo-bar");
54}