Skip to content

Instantly share code, notes, and snippets.

@thevangelist
Created September 21, 2016 10:11
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save thevangelist/8ff91bac947018c9f3bfaad6487fa149 to your computer and use it in GitHub Desktop.
Save thevangelist/8ff91bac947018c9f3bfaad6487fa149 to your computer and use it in GitHub Desktop.
JS: convert to kebab-case
const convertToKebabCase = (string) => {
return string.replace(/\s+/g, '-').toLowerCase();
}
@oravecz
Copy link

oravecz commented Jun 6, 2020

const toKebabCase = str =>
    str &&
    str
      .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
      .map(x => x.toLowerCase())
      .join('-');

Sorry @Vadorequest
toKebabCase('FOO-BAR') -> ''f-o-o-bar''

@oravecz
Copy link

oravecz commented Jun 6, 2020

str
  .replace(/([A-Z])([A-Z])/g, '$1-$2')
  .replace(/([a-z])([A-Z])/g, '$1-$2')
  .replace(/[\s_]+/g, '-')            
  .toLowerCase() 

Sorry @GerardRodes
'FOO-BAR' -> ''f-oo-b-ar''

@tehpsalmist
Copy link

@oravecz That's a shame! Do you think you have a fix handy?

@Vadorequest
Copy link

Vadorequest commented Jun 6, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment