JS para impacientes

como usar o toTitleCase no javascript es6

January 04, 2020

Converts a string to title case.

Break the string into words, using a regexp, and combine them capitalizing the first letter of each word and adding a whitespace between them.

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'

Acesse a Referência original


Está curtindo os conteúdos da Reativa? Quer que a gente te ajude a ser um dev melhor? Clique aqui.