How to Capitalize the First Letter of Each Word in a String in JavaScript

To capitalize the first letter of each word in a string in JavaScript:

  1. Split the string into an array of words with .split('').
  2. Iterate over the words array with .map().
  3. For each word, return a new word that is an uppercase form of the word’s first letter added to the rest of the word.
  4. Join the words array into a string with .join(' ').

For example:

index.js

function capitalizeWords(str) {
  return str
    .toLowerCase()
    .split(' ')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}


// Welcome To Coding Beauty
console.log(capitalizeWords('WELCOME to coding beauty'));

// JavaScript And TypeScript
console.log(capitalizeWords('JAVASCRIPT AND TYPESCRIPT'));

Our capitalizeWords() function takes a string and returns a new string with all the words capitalized.

First, we use the toLowerCase() method to lowercase the entire string, ensuring that only the first letter of each word is uppercase.

// welcome to coding beauty
console.log('WELCOME to coding beauty'.toLowerCase());

Tip: If it’s not necessary for the remaining letters in each word to be lowercase, you can remove the call to the toLowerCase() method.

Then we call the String split() method on the string to split all the words into an array.

// [ 'welcome', 'to', 'coding', 'beauty' ]
console.log('welcome to coding beauty'.split(' '));

After creating the array, we call the map() method on it, with a callback function as an argument. This function will be called and return a result for each word in the array.

In the function, we get the word’s first character with charAt(), convert it to uppercase with toUpperCase(), and concatenate it with the rest of the string.

We use the String slice() method to get the remaining part of the string. Passing 1 to slice() makes it return the portion of the string from the second (index of 1) character to the end.

// [ 'Welcome', 'To', 'Coding', 'Beauty' ]
console.log(
  'welcome to coding beauty'
    .split(' ')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
);

So map() returns an array containing all the words in the string, with each word’s first letter capitalized.

Lastly, we concatenate all the words in a single string, with the Array join() method.

Passing a space (' ') to join() separates the words by a space in the resulting string.

// Welcome To Coding Beauty
console.log(['Welcome', 'To', 'Coding', 'Beauty'].join(' '));


Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *