What I have done wrong at the attached code?

Hello everyone, I am trying to solve the “title case a sentence” challenge on Basic Algorithm Scripting. As I checked my code, it was returning the intended result but the system is not accepting it. Kindly point the issue. Thanks.

Here is my code.

function titleCase(str) {
  let statement = str.split(" ");
  let result = [];
  for(let a = 0; a < statement.length; a++){
    let word = statement[a].split("")
    if(word.length > 1){
    for(let b = 1; b < word.length; b++){
      word[0] = word[0].toUpperCase();
      word[b] = word[b].toLowerCase();
    }
    }else{
      word[0] = word[0].toUpperCase();
      // console.log(word)
    }
  result.push(word.join(""))  
  result.push(' ')
  }
let laststr = result.join("");
  return laststr;
}

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

If you have a question about a specific challenge as it relates to your written code for that challenge and need some help, click the Ask for Help button located on the challenge (it looks like a question mark). This button only appears if you have tried to submit an answer at least three times.

The Ask for Help button will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.


I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

I’ve applied some minor formatting fixes:

function titleCase(str) {
  const statement = str.split(" ");
  const result = [];

  for (let a = 0; a < statement.length; a++) {
    let word = statement[a].split("")
    if (word.length > 1) {
      for (let b = 1; b < word.length; b++) {
        word[0] = word[0].toUpperCase();
        word[b] = word[b].toLowerCase();
      }
    } else {
      word[0] = word[0].toUpperCase();
      // console.log(word)
    }
    result.push(word.join(""));
    result.push(' ');
  }
  
  const laststr = result.join("");
  return laststr;
}

console.log("***" + titleCase("I'm a little tea pot") + "***");

You should look at the output your function produces with console.log()

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