URL Slug Generation
Generate URL-friendly slugs from titles.
Basic Slug
#![allow(unused)]
fn main() {
use rok_utils::slug;
fn basic_slug(title: &str) -> String {
slug(title)
}
assert_eq!(basic_slug("Hello World!"), "hello-world");
assert_eq!(basic_slug("O'Reilly's Guide"), "oreillys-guide");
}
Custom Slug
#![allow(unused)]
fn main() {
use rok_utils::slug;
fn underscore_slug(title: &str) -> String {
slug(title, '_')
}
assert_eq!(underscore_slug("Hello World!"), "hello_world");
}
Advanced Slug with Fluent Builder
#![allow(unused)]
fn main() {
use rok_utils::str::Str;
fn advanced_slug(title: &str) -> String {
Str::of(title)
.trim()
.lower()
.replace("'", "")
.replace("&", " and ")
.replace("_", "-")
.squish()
.pipe(|s| slug(&s, '-'))
.value()
}
assert_eq!(advanced_slug(" Hello World & Friends! "), "hello-world-and-friends");
assert_eq!(advanced_slug("O'Reilly's Guide"), "oreillys-guide");
}
Complete Example
#![allow(unused)]
fn main() {
use rok_utils::str::Str;
fn generate_post_slug(title: &str, id: u64) -> String {
let slug = Str::of(title)
.trim()
.lower()
.replace("'", "")
.replace("\"", "")
.replace(" ", "-")
.replace("--", "-")
.when(|s| s.value().ends_with("-"), |s| {
// Remove trailing dash
s.pipe(|v| v.trim_end_matches('-').to_string())
})
.value();
format!("{}-{}", id, slug)
}
assert_eq!(generate_post_slug("My Blog Post!", 123), "123-my-blog-post");
}