How to Title Case a String in Javascript

March 15, 2020

Converting a string to title case essentially means capitalizing the first letter of each word. For example, changing this is a string to This Is A String. However, different use-cases require different functionality.

Title Case a String in Javascript Perserving Other Capitals

Most acronyms (ASAP, OMW) and some strings have capital letters within the word itself McDonald. In these cases, we need to preserve those capitals while only capitalizing the first character.

Title Case with Regex

The shortest way to accomplish this is to use regex to match only the first character of each string and use the built-in method .toUpperCase() to capitalize it.

ES6 Version

const toTitleCase = str => str.replace(/\b\S/g, t => t.toUpperCase());

ES5 Version

function toTitleCase(str) {
  return str.replace(/\b\S/g, function(txt) {
    return txt.charAt(0).toUpperCase();
  });
}

Title Case with For Loop

We can also use a for loop to loop over each letter of each word and uppercase only the first character using charAt(0).

function toTitleCase(str) {
  str = str.split(" ");
  for (var i = 0; i < str.length; i++) {
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
  }
  return str.join(" ");
}

Usage

const newStr = toTitleCase("we need to go ASAP");

This will generate the following title cased string:

"We Need To Go ASAP";

Title Case a String in Javascript Removing Other Capitals

In some cases, you might want to lowercase all other capital letters in the word. For example, the string yEs wE can has two incorrectly capitalized Es. The correct string should be Yes We Can.

Title Case with Regex - Remove Capitals

ES6 Version

const toTitleCase = str =>
  str.replace(
    /\w\S*/g,
    t => t.charAt(0).toUpperCase() + t.slice(1).toLowerCase()
  );

ES5 Version

function toTitleCase(str) {
  return str.replace(/\w\S*/g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
}

Title Case with For Loop Removing Capitals

function toTitleCase(str) {
  str = str.toLowerCase();
  str = str.split(" ");
  for (var i = 0; i < str.length; i++) {
    str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
  }
  return str.join(" ");
}

Usage

const newString = toTitleCase("we need to go ASAP");

This will generate the following title cased string:

"We Need To Go Asap";