Slugify a string
11 March 2022 (Updated 11 March 2022)
On this page
TLDR
You want a function that takes a given string and converts into a slug:
slugify('John Doe') // 'john-doe'
Here’s how:
def slugify(str)
str.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
end
Explanation
The slugify
function takes these steps:
- Downcase the string.
- Strip leading and trailing spaces.
- Replaces spaces with dashes.
- Remove any char that isn’t a letter, number or dash.
Tagged:
Algorithms