sajad torkamani

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