Using split() doesn't work properly

I need to title case a sentence. To do so, I’ve decided i would split the sentences by spaces, and split each of those words into letters by using a for-loop like this:
function titleCase(str) { var lower = str.toLowerCase(); var splitIntoWords = lower.split(' '); for(var i = 0; i < splitIntoWords.length; i++){ var splitIntoLetters = splitIntoWords.split(''); } }
Now when I test this, the console displays: “TypeError: splitIntoWords.split(’’) is not a function”.
This is weird because it does work with lower.split() which is written down the exact same way.

Thanks for helping.
Does anybody know why this is?

You can simply continue the operations with the lower variable. There is no need to define a new variable only to split. So something like :

var lower = str.toLowerCase().split(' ');

Should work as intented.

Your mistake is there :

var splitIntoWords = lower.split(' '); // this turn lower into an array


var splitIntoLetters = splitIntoWords.split(''); //splitIntoWords is an array, and split() is a String method, so it returns an error.

The problem you are having is that in your code as written:

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

splitIntoWords is already an array. string.split() is a string method. That is why you are getting that error.

one way to make it not throw the error is to change the line from
var splitIntoLetters = splitIntoWords.split('');
var splitIntoLetters = splitIntoWords[i].split('');

do note: that will remove that error, but the loop as written, without any other code, will simply replace splitIntoLetters with an array of the letters of each word, so when the loop is done running all you will have is an array of the last word of the sentence in the splitIntoLetters variable.


Weirdly, when I wondered how I would tackle this at the start, that was my plan, but I completely forgot to add that in. Thanks for pointing that out!

Thank you very much!

1 Like

Finished it now. This forum is amazing!

1 Like