diff options
| author | Ben Bridle <bridle.benjamin@gmail.com> | 2026-03-02 14:38:07 +1300 |
|---|---|---|
| committer | Ben Bridle <bridle.benjamin@gmail.com> | 2026-03-02 14:38:07 +1300 |
| commit | a490ead653cac5f3d1ecc25899b89431c4be3483 (patch) | |
| tree | e79eb04246b4a652672ff07a7488c4b5c21eb032 | |
| parent | 12b28c938bd28ca643cd7da32c8b054847f3b79e (diff) | |
| download | toaster-a490ead653cac5f3d1ecc25899b89431c4be3483.zip | |
Collapse consecutive hyphens in slugs
Previously, a heading or page called something like 'Name - subtitle'
would become the slug 'name---subtitle' because the hyphen is stuck
between spaces which also become hyphens. This looks silly. The new
function will generate the slug 'name-subtitle' instead.
| -rw-r--r-- | src/string_utils.rs | 18 |
1 files changed, 13 insertions, 5 deletions
diff --git a/src/string_utils.rs b/src/string_utils.rs index 2061110..cceb575 100644 --- a/src/string_utils.rs +++ b/src/string_utils.rs @@ -66,11 +66,19 @@ impl From<&str> for Name { // Turn a string into a tidy URL slug. pub fn to_slug(text: &str) -> String { - text.to_ascii_lowercase().chars().filter_map(|c| - if c.is_alphanumeric() || "-_~.+/#".contains(c) { Some(c) } - else if c == ' ' { Some('-') } - else { None } ) - .collect() + let mut string = String::new(); + let mut prev = ' '; + for c in text.to_lowercase().chars() { + let c = match c == ' ' { + true => '-', + false => c, + }; + if c.is_alphanumeric() { string.push(c) } + if "_~.+/#".contains(c) { string.push(c) } + if c == '-' && prev != '-' { string.push(c) } + prev = c; + } + return string; } // Prevent link hrefs from breaking out of quotations. |
