0

Basically, the challenge is to have an algorithm that takes in a string and that returns the beginning of each word capitalized. Simple enough, but I get stuck at how to capitalize the letter after finding the space in a loop (maybe there's a better way to do it).

Here is my code:

 var capitalize = function(string){

var split = string.split(" ");
var collection = [];
var store = [];

for(var i = 0; i < split.length; i++){

  if(split[i]){

      if(split[i] === " "){
        var init = split[i+1].toUpperCase();
        store.push(init);
        collection.push(split[i]);
      } else{
        collection.push(split[i]);
      }
  }

}

var temp = collection.join(" ");
var final = temp.charAt(0).toUpperCase() + temp.slice(1);

return final;

}

Obviously, inside my for loop, it won't let me make changes to the array that I'm iterating through. Then I tried a while loop, I tried to use array.map and it still doesn't work. I just don't seem to understand how I can capitalize the word after finding the space (" ").

Any help is appreciated.

Mabeh Al-Zuq Yadeek
  • 46
  • 4
  • 16
  • 28

3 Answers3

3

Can't you split the string by " " and make the first letter of each collection entry a uppercase?

Take a look here how the make the first letter uppercase.

Community
  • 1
  • 1
Wavemaster
  • 1,794
  • 16
  • 27
0

Why you want to do this in JS when you can do this in CSS

p.capitalize {
    text-transform: capitalize;
}

<p class='capitalize'>
  hello how are you?
</p>

jsfiddle

brk
  • 48,835
  • 10
  • 56
  • 78
0

No need for all that variables

Just:

function (str){ return str.replace(str.charAt(0), str.charAt(0).toUpperCase()) }

will do.

javaguest
  • 399
  • 2
  • 8