Tell us what’s happening:
I am trying to chain .substring() but it is not working, in console I see substring navtive function, which IMO means I haven’t executed it, but I did. I am not sure why I am getting such output. I tried to chain .slice() and I got the same message. Why?
Your code so far
function titleCase(str) {
//split each array where there is space
str = str.split(" ")
// //loop each word and make first word uppercase
str.forEach((word)=>{
console.log(word.slice(0,1).toUpperCase().substring(1,4));
})
//join back word back into sentence
return str;
}
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/113.0.0.0 Safari/537.36
Challenge: Basic Algorithm Scripting - Title Case a Sentence
When you apply methods to a string, it creates a new string, without modifying the original string, so you’d need to reassign str (as you did above when you split it).
forEach always returns undefined (and is not chainable), so is not the correct method to use here. I’d try map instead. You can use slice and substring but you’d need to use concatenation (i.e. capitalise the first letter as you are and then concatenate the substring).
You also need to ensure that the rest of each word is lower case (as per instructions).
Then the new value of str is an array. You haven’t mutated the original string, just reassigned the value of the variable str.
Personally, I’d rather do:
let arr = str.split(" ")
Because I like my arrays to have array-like names and strings to have string-like names etc.
My point though is that:
str.map(word => { //callback function })
Doesn’t mutate the value of str either. If you console.log(str) immediately after this line, you’ll see that str still holds the same value. So, you need to assign this map function output to a variable, whether it’s reassigning str or something else. So you’d at least need something like: