Titlecase string

JavaScript, String, Regexp · Oct 22, 2020

Converts a string to title case.

const toTitleCase = 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.charAt(0).toUpperCase() + x.slice(1))
    .join(' ');
toTitleCase('some_database_field_name'); // 'Some Database Field Name'
toTitleCase('Some label that needs to be title-cased');
// 'Some Label That Needs To Be Title Cased'
toTitleCase('some-package-name'); // 'Some Package Name'
toTitleCase('some-mixed_string with spaces_underscores-and-hyphens');
// 'Some Mixed String With Spaces Underscores And Hyphens'

More like this

  • JavaScript String Casing

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

    Collection · 7 snippets

  • Snakecase string

    Converts a string to snake case.

    JavaScript, String · Jun 28, 2021

  • 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