2

I have this code :

//make first letter of each word capital
function titleCase(str) {
    /*
     *  1. change all letters to lower case
     *  2. split words
     *  3. set each 1st letter to Capital
     *  4. combine array back into string
     */
    arr = [];
    str.toLowerCase();

    arr = str.split(" ");

    for (var index = 0; index < arr.length; index++) {
        arr[index].charAt(0).toUpperCase();
    }

    str= arr.join(" ");
    return str;
}
console.log(titleCase("Potato potato potato"));

And I don't understand why toLowerCase() and toUpperCase() are not working. What am I doing wrong ?

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
krumpec
  • 143
  • 1
  • 2
  • 6
  • What you are trying to do in `str.toLowerCase();` ? – Om Sao Sep 26 '17 at 13:55
  • 2
    `toLowerCase()` and `toUpperCase()` does not affect the value of the string `str` itself. You need to assign back the value to `str` after converting to lower case or upper case. – Hassan Imam Sep 26 '17 at 13:56
  • 1
    Possible duplicate of [Title case a sentence?](https://stackoverflow.com/questions/31495239/title-case-a-sentence) – Rajesh Sep 26 '17 at 13:56

4 Answers4

3

There are 2 updates required

  1. Reassign str.toLowerCase() to str
  2. Reassign updated array value back in array.

Please note, until and unless you reassign the values, the original value does not change. Hence, the result remained unaffected.

//make first letter of each word capital
function titleCase(str) {
/*
1. change all letters to lower case
2. split words
3. set each 1st letter to Capital
4. combine array back into string
*/
    arr = [];
    str = str.toLowerCase(); // **** Problem 1 - Reassigning

    arr = str.split(" ");

    for (var index = 0; index < arr.length; index++) {
       // **** Problem 2 - Reassigning
       arr[index] = arr[index].charAt(0).toUpperCase() + arr[index].slice(1);
    }

    str= arr.join(" ");
    return str;
}
console.log(titleCase("Potato potato potato"));
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

You need to reassign (overwrite) the value inside the array after you change it. Otherwise, the array remains unchanged. Besides, you forgot to add the rest of the string (arr[index].slice(1)) to the uppercased letter.

function titleCase(str) {
    let arr = [];
    str.toLowerCase();

    arr = str.split(" ");

    for (var index = 0; index < arr.length; index++) {
        arr[index] = arr[index].charAt(0).toUpperCase() + arr[index].slice(1); // <-- Changes
    }

    str= arr.join(" ");
    return str;
}
console.log(titleCase("Potato potato potato"));

EDIT

Here is my own ES6 one-liner version :

titleCase = str => str.trim().split(" ").map( word => word.charAt(0).toUpperCase() + word.slice(1) ).join(" ")
    
console.log(titleCase("Potato potato potato"));

Explanation :

titleCase = str => str
                   .trim() // Removes extra spaces
                   .split(" ")
                   .map( word =>
                        word.charAt(0).toUpperCase() + word.slice(1) // Uppercases 1st letter, adds the rest of the word, returns the whole
                   )
                   .join(" ") // Reforms a string
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • 1
    Just a pointer. Do not rush into posting an answer. An answer is incomplete without explanation. This attracts unwanted votes/comments like this. Its a good practice to incrementally update answer, but make sure your 1st cut justifies the term answer – Rajesh Sep 26 '17 at 13:59
  • you forgot to lowercase the rest of the words in your one liner solution. Again: Don't rush. Think about your solution and post it when you are ready. – Joshua K Sep 26 '17 at 14:10
0

short solution:

var titleCase = (str)=>str.toLowerCase().split(' ').map(word=>word.charAt(0).toUpperCase()+word.slice(1)).join(' ');

calling:

titleCase('Potato potato potato');

Splitting the string by space and map a lambda to the resulting array. The lambda turns up the first letter and append the rest of the word.


as pointed out in the comments:

var titleCase = (str)=>str.toLowerCase().split(' ').reduce((currentString, word)=>currentString+(currentString ? ' ':'')+word.charAt(0).toUpperCase()+word.slice(1));

this works also and loops only one time.

Joshua K
  • 2,407
  • 1
  • 10
  • 13
0

you can simply do

function convert(str){
    return str.split(' ').map(e => e.replace(/([A-Za-z])(\w+)/, (x, y, z) => y.toUpperCase()+z.toLowerCase())).join(' ');
}

console.log(convert('Potato potato pOtato'))
marvel308
  • 10,288
  • 1
  • 21
  • 32