Basic Algorithm Scripting - Title Case a Sentence

Hi all, would need your help to review my code. So far this is what I got and after running the tests, the system does not accept it even though the output requirements are all met. Can someone help identify the issue here?

Your code so far

function titleCase(str) {
  var arr = str.split(" ");
  var arr2 = [];

  for (let i = 0; i < arr.length; i++){
    for (let j = 0; j < arr[i].length; j++){
      if (j == 0){
      } else {
    arr2.push(" ");

  return arr2.join("");


console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: Basic Algorithm Scripting - Title Case a Sentence

Link to the challenge:

if you change the space here to a character like # you can see where all the spaces are getting inserted.
It seems you are inserting an extra space at the end of the sentences.


Thanks! Solved the issue by adding a pop(" ") statement before returning the answer but not sure if that will be ideal. Any suggestions you have to better improve the code?

there are multiple ways that you can try to solve this.
For eg. you could have used a very simple loop. (one loop that loops thru the characters of the string. You can think about this and figure out the algorithm.)

Another option would have been to use a regex. Again, you can think about that to see how it would work.

Just looking at your code as-is, there are no comments so I have to spend time to try to determine what your algorithm really is. But my impression is that you could have lowercased the whole sentence first, then just looped once (no nested looping) over the words to just make the first letter a capital using the arr[i][0] to do that.

Another comment would be that you are relying on exactly one space between each word. What if someone makes a mistake and enters two spaces for eg between two words…

So finding more flexible ways to deal with this algorithm would be my major suggestion, and following this, try to add comments to explain your algorithm

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.