Snakecase string

JavaScript, String, Regexp · Jun 28, 2021

Converts a string to snake case.

const toSnakeCase = 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('_');
toSnakeCase('camelCase'); // 'camel_case'
toSnakeCase('some text'); // 'some_text'
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens');
// 'some_mixed_string_with_spaces_underscores_and_hyphens'
toSnakeCase('AllThe-small Things'); // 'all_the_small_things'
toSnakeCase('IAmEditingSomeXMLAndHTML');
// 'i_am_editing_some_xml_and_html'

More like this

  • JavaScript String Casing

    Convert between the most common string casing formats with pure JavaScript and a sprinkle of regular expressions.

    Collection · 6 snippets

  • Titlecase string

    Converts a string to title case.

    JavaScript, String · Oct 22, 2020

  • Camelcase string

    Converts a string to camelcase.

    JavaScript, String · Oct 22, 2020

  • Pascalcase string

    Converts a string to pascal case.

    JavaScript, String · Sep 8, 2021