Capitalize First Letter Of Each Word Using JavaScript

Introduction

 
This is one of the most common programming interview questions that you would have come across. So here we will be seeing how we can capitalize on the first word in a string using 3 different approaches.
 
Here is the code sample that shows you how to capitalize the first word in a given string. 
 
EXAMPLE 1
  1. function capitalize(input) {  
  2.     var words = input.split(' ');  
  3.     var CapitalizedWords = [];  
  4.     words.forEach(element => {  
  5.         CapitalizedWords.push(element[0].toUpperCase() + element.slice(1, element.length));  
  6.     });  
  7.     return CapitalizedWords.join(' ');  
  8. }  
OUTPUT
 
Capitalize First Letter Of Each Word Using JavaScript
 
 Capitalize First Letter Of Each Word Using JavaScript
 
Here is a second code sample that shows you how to capitalize on the first word in a given string using an approach where we check for the previous character in a string and capitalize on the current character if the previous character is a space.
 
EXAMPLE 2
  1. function capitalize(input) {  
  2.     var CapitalizeWords = input[0].toUpperCase();  
  3.     for (var i = 1; i <= input.length - 1; i++) {  
  4.         let currentCharacter,  
  5.             previousCharacter = input[i - 1];  
  6.         if (previousCharacter && previousCharacter == ' ') {  
  7.             currentCharacter = input[i].toUpperCase();  
  8.         } else {  
  9.             currentCharacter = input[i];  
  10.         }  
  11.         CapitalizeWords = CapitalizeWords + currentCharacter;  
  12.     }  
  13.     return CapitalizeWords;  
  14. }  
OUTPUT
 
Capitalize First Letter Of Each Word Using JavaScript
 
Here is another code sample which is shorthand of what we have done above and is achieving the same results using fewer lines of code.
 
EXAMPLE 3
  1. function capitalize(input) {  
  2.     return input.toLowerCase().split(' ').map(s => s.charAt(0).toUpperCase() + s.substring(1)).join(' ');  
  3. }  
OUTPUT
 
Capitalize First Letter Of Each Word Using JavaScript
 
I hope you find this blog helpful. Stay tuned for more … Cheers!!