Learning JS (Title Case Sentence)

Learning JS (Title Case Sentence)
0

#1

I’m trying to solve this problem with all the things I’ve learned so far, but my code is not working and the ways people are solving it is indeed very different.

My question here really is, why isn’t the following code doing the trick?
Just trying to understand the logic…

``````
function titleCase(str) {
var newArray = str.toLowerCase().split(" ");

//Going through the array//
for (var i = 0; i < newArray.length; i++){
for (var j = 0; j < newArray[i].length; j++){

//if index is in index 0 (letter) of the word//
if (newArray[i][j] == newArray[i][0]){

//change letter to uppercase//
newArray[i][j].toUpperCase();
}

}
}
return newArray;

}

titleCase("i'm a little tea pot");``````

#2

``````function titleCase(str) {
var newArray = str.toLowerCase().split(" ");

//Going through the array
for (var i = 0; i < newArray.length; i++){
for (var j = 0; j < newArray[i].length; j++){

//if index is in index 0 (letter) of the word
console.log(newArray[i][j], newArray[i][0], newArray[i][j] == newArray[i][0])
if (newArray[i][j] == newArray[i][0]){
// the above is asking if current letter of current word equal to current word's first letter.  The problem with this logic is what if a word has the same letter multiple times as the first letter?

//change letter to uppercase
newArray[i][j].toUpperCase(); // try to capitalize a part of a string.
// the above will not do anything, because strings are immutable
// you will need to replace the entire word with what you want
// it to look like by reassigning it to the current element in newArray
}
}
}
return newArray; // this will return an array, but you need to be returning a string here.
}

titleCase("i'm a little tea pot");
``````

#3

Hey, congrats on your pursuit of JS! It will yield great dividends for your future.
I would encourage you to look at using map(),split(),join(), toLowerCase() and toUpperCase().
These methods could help clean up your code and save a lot of typing which is always a good thing. Hope this helps.
Happy Coding!

#4

Here is my solution:

``````function titleCase(str) {
let x = str.split(' ');
for (let i = 0; i < x.length; i++){
if (x[i].length > 1) {
let firstLetterUpper = x[i].charAt(0).toUpperCase()
let wordWithoutFirst = x[i].substring(1, x[i].length)
x[i] = firstLetterUpper + wordWithoutFirst.toLowerCase()
}
else x[i] = x[i].charAt(0).toUpperCase()
}
return x.join(' ')
}

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

``````