ckperez
ckperez

Reputation: 13

Splitting sentence string into array of words, then array of words into arrays of characters within the array of words

I'm working through a problem on freecodecamp.com, and I want to see whether my code so far is doing what I think it is doing...

function titleCase(str) {
  var wordArr = str.split(' '); // now the sentences is an array of words
  for (var i = 0; i < wordArr.length; i++) { //looping through the words now...
    charArr = wordArr[i].split(''); //charArr is a 2D array of characters within words?
    return charArr[1][1];
  }

}

titleCase("a little tea pot"); // this should give me 'i', right?

Again, this is just the beginning of the code. My goal is to capitalize the first letter of each word in the parameter of titleCase();. Perhaps I'm not even going about this right at all.

But... is charArr on line 4 a multidimensional array. Did that create [['a'],['l','i','t','t','l','e'],['t','e','a','p','o','t']]?

Upvotes: 1

Views: 2588

Answers (3)

Rana
Rana

Reputation: 1755

You can do the following:

function titleCase(str) {
    var newString = "";
    var wordArr = str.split(' ');
    for (var i = 0; i < wordArr.length; i++) { //looping through the words now...
        var firstLetter = wordArr[i].slice(0,1); // get the first letter
        //capitalize the first letter and attach the rest of the word
        newString += firstLetter.toUpperCase() + wordArr[i].substring(1) + " ";
    } 
 return newString;
} 

Also you need to remove the return statement in your for loop because the first time the for loop goes over the return statement, it will end the function and you will not be able to loop through all the words


Here you can learn more about string.slice() : http://www.w3schools.com/jsref/jsref_slice_string.asp

Upvotes: 0

WirelessKiwi
WirelessKiwi

Reputation: 1048

In addition to ABR answer (I can't comment yet) :

charArr is a one-dimensional array, if you want it to be a 2d array you need to push the result of wordArr[i].split(''); instead of assigning it.

charArr.push(wordArr[i].split(''));

And don't forget to initialize charArr as an empty array

Upvotes: 1

iddqd
iddqd

Reputation: 1305

Few issues :
1. Your return statement will stop this after one iteration.
2. If one of the words have fewer then 2 letters (like the first one in your example, which is 'a') - you will get an exception at charArr[1][1].

Other then that, it is mostly ok. It would probably help you to download a tool like firebug and test your code live...

Upvotes: 1

Related Questions