Sentencecase string

JavaScript, String, Regexp · Mar 27, 2023

Converts a string to sentence case.

const toSentenceCase = str => {
  const s =
    str &&
    str
      .match(
        /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
      )
      .join(' ');
  return s.slice(0, 1).toUpperCase() + s.slice(1);
};
toSentenceCase('some_database_field_name'); // 'Some database field name'
toSentenceCase('Some label that needs to be title-cased');
// 'Some label that needs to be title cased'
toSentenceCase('some-package-name'); // 'Some package name'
toSentenceCase('some-mixed_string with spaces_underscores-and-hyphens');
// 'Some mixed string with spaces underscores and hyphens'

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

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

  • 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