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:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence
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.
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");