toTitleCase()

Last updated: July 20, 2021

Description

Converts a given string to title case.

const toTitleCase = str =>
  str
    .toLowerCase()
    .match(/[a-z](?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
  • We create a function the accepts a string as its parameter
  • We then take the string and transform all characters to lowercase
  • From the lowercased string, we break the string into an array of words based on the regular expressions we passed from the match function
  • We map through each word from the array wherein we take the "index zero" or the first letter of every word and converts it to uppercase
  • We take the converted uppercase letter and append it to the sliced word starting from "index one" or the second letter of every word
  • The map returns a new array of uppercased words so we just need to join all the words from the array by adding space to create a sentence

Parameters

str - the word or sentence in a string format

Return Values

Returns a title-cased string.

Usage

You can pass a word or sentence as an argument:

toTitleCase('The world is your oyster');
// Result: "The World Is Your Oyster"

You can pass an all Caps word or sentence as an argument:

toTitleCase('CHANSU WA JIBUN DE TSUKURU MONO');
// Result: "Chansu Wa Jibun De Tsukuru Mono"

You can pass an underscored string as an argument:

toTitleCase('sample_database_field_name');
// Result: "Sample Database Field Name"

You can pass a hyphenated string as an argument:

toTitleCase('sample-variable-name');
// Result: "Sample Variable Name"

You can pass a mixed string with spaces, uppercase, underscores, and hyphens as an argument:

toTitleCase('sample-mixed_string with spaces UPPERCASE_underscores-and-hyphens');
// Result: "Sample Mixed String With Spaces Uppercase Underscores And Hyphens"

Live Example

Hey, did you find this shortcode useful? I would appreciate if you could share this to your networks.