Charat() HELP needed SOLVED comment pls

Hey. don’t understand why charAt() isn’t workring here:

function titleCase(str) {
  str = str.split (' ');
var oneWord = [];
  for (var x=0; x<str.length; x++) {
    oneWord.push (str[x].toLowerCase().replace (/*oneWord[0].charAt(0)*/,'_')); //commented part gives error
      }
 return oneWord;
}
titleCase ("random string");

The error is

Uncaught TypeError: Cannot read property 'charAt' of undefined

This error is not about charAt - rather the object on which charAt is called - so oneWord[0] is undefined

A console.log(oneWord[i]) in the loop body shows the problem

Thanks. But now something happened with loop (?):frowning: If I understand correctly it goes only once. Could you take a look pls?

function titleCase(str) {
str = str.split (' ');
var oneWord = [];
var endLine = 0; //
for (var x=0; x<str.length; x++) {
oneWord.push (str[x].toLowerCase());
return oneWord[x].replace (oneWord[x].charAt(),oneWord[x].charAt(0).toUpperCase()); 
}
//return oneWord; //it returns only the first word for some reason
}
titleCase ("random string"); //it shows the first letter uppercased as it should but only displays the first word 'Random'

Once a return is executed in a function, the function is done - a walkthrough helps uncover unexpected program behavior

See this post for a walkthrough example

1 Like

Thanks! Finally done with this one!

Btw, if any would like to comment/view my code it’s here:

function titleCase(str) {
str = str.split (’ ‘);
var oneWord = [];
for (var x=0; x<str.length; x++) {
oneWord.push (str[x].toLowerCase());
}
for (var c = 0; c < oneWord.length; c++){
oneWord[c] = oneWord[c][0].toUpperCase() + oneWord[c].substring(1);
}
return oneWord.join(’ ');
}

titleCase (“sHoRt AnD sToUt”);

Comments inline

1.  function titleCase(str) {
// don't reassign input parameters - use a new variable
// don't change the type of a variable - use a new variable for the array 
2.  str = str.split (' ');
// use let instead of var
3.  var oneWord = [];
// use i, j, k for index variables
// lowercase the string before split to eliminate this loop
4.  for (var x=0; x<str.length; x++) {
5.    oneWord.push (str[x].toLowerCase());
6.  }
7.  for (var c = 0; c < oneWord.length; c++){
  // use slice instead of substring
8.    oneWord[c] = oneWord[c][0].toUpperCase() + oneWord[c].substring(1);
9.  }
10. return oneWord.join(' ');
11. }