Title Case a Sentence (Help)

Hi, can anyone explain why the code below not working? And i also get this error four times when i run the test : Cannot assign to read only property ‘0’ of string ‘i’m’

function titleCase(str) {
  str = str.toLowerCase();
  let arr = str.split(" ");
  let newStr = "";

  for (let i = 0; i < arr.length; i++) {
    let temp = arr[i][0].toUpperCase();
    arr[i][0] = temp.toUpperCase();
    newStr = newStr + " " + arr[i];

  return newStr;

titleCase("I'm a little tea pot");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:

I’ve edited your post 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 easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


It looks like you’re probably adding a space at the beginning of your newStr.

But even the first test, which is this:

titleCase(“I’m a little tea pot”)` should return a string.

is not passed with the code i wrote in the first post.

Put some console.log statement in your code to check what values certain variables have at certain points in your code. Then use your browser’s console (Ctrl+Shft+J in Chrome) to view the results of those statements.

For starters, you should add console.log(newStr) on the line before your return statement, so you can see what your function is returning and go from there.

1 Like

Thank you for answers guys. After learning some js methods I passed the test the way below.

function titleCase(str) {
return str.toLowerCase().split(/[^a-z']/i).map(x => (x[0].toUpperCase() + x.slice(1))).join(" ");
titleCase("I'm a little tea pot");