Skip to main content

How to Capitalize the First Letter of a Word in JavaScript

Capitalizing the first letter of a word—often called "title case" or "proper case"—is a common text formatting task in JavaScript. You might need to format a user's name, a title, or a sentence. While CSS can handle this visually, you often need to perform the transformation directly on the string data itself.

This guide will teach you how to build a simple and reusable function to capitalize a single word. You will then learn how to apply this function to more complex tasks, like capitalizing every word in a sentence or every element in an array, using standard JavaScript methods like .split(), .map(), and .join().

Core Task: Capitalizing a Single Word

The fundamental building block for all of these tasks is a function that can capitalize a single word. The logic is simple:

  1. Get the first character of the string and convert it to uppercase.
  2. Get the rest of the string (from the second character onwards).
  3. Concatenate the two parts.

The capitalize Function

function capitalize(word) {
// Ensure the word is a string and not empty
if (typeof word !== 'string' || word.length === 0) {
return '';
}

const firstLetter = word.charAt(0).toUpperCase();
const restOfWord = word.slice(1).toLowerCase();

return firstLetter + restOfWord;
}

console.log(capitalize('hello')); // Output: Hello
console.log(capitalize('WORLD')); // Output: World
console.log(capitalize('javaScript')); // Output: Javascript

How it Works:

  • word.charAt(0) gets the first character.
  • .toUpperCase() converts it to uppercase.
  • word.slice(1) gets the rest of the string, starting from the second character (index 1).
  • .toLowerCase() is optional but recommended to ensure the rest of the word is in a consistent lowercase format.

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

Now that we have our capitalize helper function, we can apply it to every word in a sentence. The process is a classic "split-map-join" chain.

  1. Split the sentence into an array of words.
  2. Map over the array, applying our capitalize function to each word.
  3. Join the array of capitalized words back into a single string.
function capitalize(word) {
if (typeof word !== 'string' || word.length === 0) return '';
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}

function toTitleCase(sentence) {
if (typeof sentence !== 'string' || sentence.length === 0) return '';

return sentence
.split(' ')
.map(word => capitalize(word))
.join(' ');
}

const mySentence = "the quick brown fox.";
const titleCased = toTitleCase(mySentence);

console.log(titleCased);
// Output: The Quick Brown Fox.

How to Capitalize Each Word in an Array

The logic for an array of words is even simpler. Since the data is already in an array, we just need to use the .map() method to apply our capitalize function to each element.

function capitalize(word) {
if (typeof word !== 'string' || word.length === 0) return '';
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}

const names = ['john', 'JANE', 'smith'];

// Use .map() to create a new array with the transformed names
const capitalizedNames = names.map(name => capitalize(name));

console.log(capitalizedNames);
// Output: [ 'John', 'Jane', 'Smith' ]
note

Important: The .map() method is the best practice for this because it is immutable—it does not change the original names array but instead returns a new array with the results.

Alternative Method: The String.replace() with Regex

For capitalizing words in a sentence, you can also use a clever regular expression with the .replace() method. This is a more advanced but very concise solution.

function toTitleCaseRegex(sentence) {
if (typeof sentence !== 'string' || sentence.length === 0) return '';

// This regex finds the first letter of the string OR the first letter after a space
return sentence.replace(/(^\w|\s\w)/g, match => match.toUpperCase());
}

const mySentence = "the quick brown fox.";
const titleCased = toTitleCaseRegex(mySentence);

console.log(titleCased); // Output: The Quick Brown Fox.

How the Regex Works:

  • /(^\w|\s\w)/g: The pattern to find.
    • ^: Start of the string.
    • \w: Any word character.
    • |: Acts as an "OR".
    • \s: A whitespace character.
    • g: The global flag, to ensure it replaces all matches, not just the first one.
  • match => match.toUpperCase(): A replacer function that is called for every match found. It takes the matched character and returns its uppercase version.

Conclusion

Capitalizing words is a common formatting task that is best solved by creating a small, reusable helper function.

To recap the best practices:

  1. Create a core capitalize(word) function that handles a single word. This makes your code clean and reusable.
  2. To capitalize a sentence, use the split-map-join pattern: sentence.split(' ').map(capitalize).join(' ').
  3. To capitalize an array of words, use the .map() method: myArray.map(capitalize).

While a regex solution is also powerful for sentences, the split-map-join approach is often more readable and easier for developers to understand and maintain.