2

I'm trying to capitalise the first letter of each word in a sentence. However, the output I got from my code below is: "I'm a little teapot". I tried finding detailed explanations of how the index argument for the callback function for the map function works but found none. I want to instruct it to capitalise the letter if the element before it is a space. What's wrong with my code?

function titleCase(str) {
str= str.toLowerCase().split("");

var newArr= str.map( function(i,j){

if ( j===0 ){
return i.toUpperCase();}
else if (str[j--]===" "){
return i.toUpperCase();
}
 return i;

});

return newArr.join("");
}


console.log(titleCase("i'm a little tea pot"));
Emily
  • 23
  • 2

1 Answers1

-1

That's crazy here.

else if (str[j--]===" ") {

You are modifying the j value. You shouldn't do that. You should do:

else if (str[j-1]===" ") {

Also, it is a post decrement operator. This is highly dangerous, as it leads to infinite looping. Plus, this always gives the current value, which applies the upper case on the space.

Making that small change fixed it:

function titleCase(str) {
  str = str.toLowerCase().split("");
  var newArr = str.map(function(i, j) {
    if (j === 0) {
      return i.toUpperCase();
    } else if (str[j-1] === " ") {
      return i.toUpperCase();
    }
    return i;
  });
  return newArr.join("");
}

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

Output:

I'm A Little Tea Pot
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252