How to Title Case a String in Javascript

March 15, 2020

javascript

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

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

ES5 Version

js
1.function toTitleCase(str) {
2. return str.replace(/S/g, function(txt) {
3. return txt.charAt(0).toUpperCase();
4. });
5.}

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).

js
1.function toTitleCase(str) {
2. str = str.split(" ");
3. for (var i = 0; i < str.length; i++) {
4. str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
5. }
6. return str.join(" ");
7.}

Usage

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

This will generate the following title cased string:

js
1."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 Capital

s

ES6 Version

js
1.const toTitleCase = str =>
2.str.replace(
3. /wS*/g,
4. t => t.charAt(0).toUpperCase() + t.slice(1).toLowerCase()
5.);

ES5 Version

js
1.function toTitleCase(str) {
2. return str.replace(/wS*/g, function(txt) {
3. return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
4. });
5.}

Title Case with For Loop Removing Capitals

js
1.function toTitleCase(str) {
2. str = str.toLowerCase();
3. str = str.split(" ");
4. for (var i = 0; i < str.length; i++) {
5. str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
6. }
7. return str.join(" ");
8.}

Usage

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

This will generate the following title cased string:

js
1."We Need To Go Asap";