nd / nd-core/src/slug.rs

raw file 913 bytes
/// Turn a project name into a url-friendly slug: "My Cool App!" -> "my-cool-app".
pub fn slugify(input: &str) -> String {
    let mut out = String::new();
    let mut last_dash = true; // swallow leading separators
    for c in input.chars().flat_map(|c| c.to_lowercase()) {
        if c.is_ascii_alphanumeric() {
            out.push(c);
            last_dash = false;
        } else if !last_dash {
            out.push('-');
            last_dash = true;
        }
    }
    while out.ends_with('-') {
        out.pop();
    }
    if out.is_empty() {
        "project".into()
    } else {
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn basics() {
        assert_eq!(slugify("My Cool App!"), "my-cool-app");
        assert_eq!(slugify("a__b"), "a-b");
        assert_eq!(slugify("  --__  "), "project");
        assert_eq!(slugify("TODO-Tracker"), "todo-tracker");
    }
}