(JS) Return a string with the first letter of each word capitalized, with the rest of the other word in lower case

·

4 min read

Here the code:

function titleCase(str) {
  let lowArray = str.toLowerCase().split(" ");
  let outcome = lowArray.map(function(val){
    return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
  });
  return outcome.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

//I'm A Little Tea Pot

So we need to create a function that capitalizes the first letter of a given string and keeps in a small letter the remain part of the string.

To achieve this we are going to use the following JS methods:

  • toLowerCase() ;
  • split() ;
  • map() ;
  • charAt()
  • replace() ;

STEP 1 (declare the function)

function titleCase(str)

Function created with the line of code above, this function accepts one argument (str);

STEP 2 ( lower case all letters of the string and split every word in splitted strings):

let lowArray = str.toLowerCase().split(" ");

We need to declare a variable let lowArray. Inside the variable we are going to store all the str values and with the dot notation we are going to use toLowerCase() method that will lower case all letter of any string str and again with the dot notation we are going to use the split() method. The split() method will split all the word of the string and will remove the white space, since as argument we are passing the white space as separator(" ") .

STEP 3 (use of the map() method):

 let outcome = lowArray.map(function(val){
    return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
  });

The map() method is a very powerful method that associated to an array, in this case with the dot notation to lowArray, will create a new array and will call the function for every single element of that array.

The function created will use the replace() method. This method takes two argument, the first will search for the value the second will replace the value found.

As argument to the replace() method we are going place as first argument val.charAt(0) which use the val.charAt(0) method which give us the value of the indexed element in the array and as second argument (the one that replace) the val.charAt(0).toUpperCase() which will replace the element 0 with an upper case value.

STEP 4 (Put together the splitted array using the join() method):

  return outcome.join(" ");

Now we have an array filled with many splitted string. To have back all the string as one we use the join(" ") . The join() method is exactly the opposite of the split() method, so to restabilish the proper space inside the newly formed string join() will take as argument (" ") an empty string with one space.