I know there’s probably a 100% more elegant way to complete this task, but I’m trying to learn why my method is not working. I’m trying to split the string, iterate though and capitalize atChar0 on each substring. That’s the part that isn’t working - the capitalization. Am I mistaken that you can iterate through substrings in such a manner?
Your code so far
function titleCase(str) {
var augStr = str.toLowerCase().split(' ');
//console.log(augArr);
for (i = 0; i < augStr.length; i++){
augStr[i].charAt(0).toUpperCase();
}
//console.log(augStr);
return augStr.join(' ');
}
titleCase("I'm a little tea pot");
Hi,
.toUpperCase() does not change the original string. It makes a copy and sends it back UPPER CASE as a return value. (Same for charAt() too - makes a copy and returns it).
Short answer is that strings cannot be changed (mutated). You can make a new string from parts and even reassign that new string to the same variable name you were using for the old one.
Good luck! You look to be very close to solving this one.
let myString = "lower";
let newString = myString.toUpperCase();
console.log(myString); // "lower"
console.log(newString); // "LOWER"
myString = newString;
console.log(myString); //"LOWER"
You are successfully copying the first letter and converting to upper case. You are not saving that though.
Well, I did it. I’m sure it’s a very extraneous, roundabout way. Just curious, how would I make the code more efficient/elegant using the same approach? Or is this just a terrible idea in general? lol
function titleCase(str) {
var tempArr = [];
var finalArr = [];
var augArr = str.toLowerCase().split(' ');
//console.log(augArr);
for (i = 0; i < augArr.length; i++){
for (j = 0; j < (augArr[i].length); j++){
if (j == 0){
tempArr.push(augArr[i].charAt(0).toUpperCase());
} else {
tempArr.push(augArr[i].charAt(j));
} }
finalArr.push(tempArr.join(''));
tempArr.length = 0;
}
return finalArr.join(' ');
}
titleCase("I'm a little tea pot");
First, You need to wrap your working code in above post in spoiler tags (gear icon menu) so others don’t see your working code accidentally.[spoiler] stuff here [/spoiler]
Good job!
I probably would have just altered your original code like this…
function titleCase(str) {
var augStr = str.toLowerCase().split(' ');
//console.log(augArr);
for (i = 0; i < augStr.length; i++){
augStr[i] = augStr[i].charAt(0).toUpperCase() + augStr[i].slice(1); // <---this line
}
//console.log(augStr);
return augStr.join(' ');
}
Either way you got it. You understood the immutability of strings thing and worked around it. Usually once you get a working solution it does not hurt to spend time trying to make that solution better.
Shorter does not always equal better especially if at expense of clarity. Efficiency is good. Speed is good. Clarity is good. If you can make it reusable elsewhere all the better.