Write a function that accepts a string. The function should capitalize the first letter of each word in the string and return the result.

Hrusikesh Swain
2 min readNov 25, 2022

--

Examples:

  • capitalize(‘a short sentence’) → ‘A Short Sentence’
  • capitalize(‘a lazy fox’) → ‘A Lazy Fox’
  • capitalize(‘look, it is working!’) → ‘Look, It Is Working!’

This is one of the common important questions asked in javascript interviews let's get it done below by following different approaches

First Approach

function capitalize(str) {
//getting the array of chars from string by splitting it with space
const array = str.split(" ");
//creating an empty array to make it more easier
const arrayB = [];
//looping through the array
for(let item of array){
//getting the first element by index and convert it into uppercase char
//getting rest of chars from the string anf adding it with the first one
arrayB.push(item[0].toUpperCase()+item.slice(1));
}
// returning new array with uppercase char of first char of each word
return arrayB.join(" ");
}
console.log(capitalize('a short sentence'));

Second Approach

This is going to be a little bit tricky where we are going to loop through the original string and check if the previous char is a space then capitalize the char otherwise do nothing just add it

function capitalizeWord(str){
//for the first char of sentence we need to manully capitalize it as there is no space before it
// the regex exp is added to check if first char is a letter not like ? or anything else used in some other languages
// like spanish lang where a sentence can be start with ?
let tempStr = str[0].match(/[a-z]/i) ? str[0].toUpperCase() : str[0];
//looping through rest of the elements of string
for(let i=1; i<str.length;i++){
//checking if previous item is a space the capitalize and add it to temp string
if(str[i-1] === " "){
tempStr = tempStr+str[i].toUpperCase();
}else{
tempStr = tempStr+str[i];
}
}

return tempStr;
}

console.log(capitalizeWord('a short sentence'));

I think the second approach is the best one which needs a little bit of practice so if asked in any javascript interview any such type of questions go with the second approach.

--

--

Hrusikesh Swain

Tech enthusiast interested in Android ,React, Javascript, Node , AWS etc.