Slugify a string
11 March 2022 (Updated 8 September 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 in Ruby:
def slugify(str)
str.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '')
end
Here’s how in JavaScript / TypeScript:
export function slugify(str: string) {
return str
.toLowerCase()
.replace(/\s/g, '-')
.replace(/[^\w-]/g, '')
}
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:
Snippets
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment