Mabeh Al-Zuq Yadeek
Mabeh Al-Zuq Yadeek

Reputation: 84

Stuck with a challenge that has me capitalizing the beginning of each word

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.

Upvotes: 0

Views: 65

Answers (3)

javaguest
javaguest

Reputation: 399

No need for all that variables

Just:

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

will do.

Upvotes: 0

brk
brk

Reputation: 50291

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

Upvotes: 0

Wavemaster
Wavemaster

Reputation: 1824

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.

Upvotes: 3

Related Questions