0

I'm learning Javascript here. My task as of right now is to take a given string and capitalize the beginning of each word, and IF the rest of the word is already caps, put it into lowercase.

What I have so far:

function titleCase(str){
    var arrayify = str.split('');
    arrayify.forEach(function(current, index){
        for (var x = 0; x < current; x++){
            var caps = current[x];
            return caps;
        } 
    });
}

My test strings:

  • I'm a little tea pot

  • sHoRt AnD sToUt

  • HERE IS MY HANDLE HERE IS MY SPOUT

What I've tried:

function titleCase(str){
   str.split(' ').map(s => chartAt(0).toUpperCase() + s.slice(1)).join(' '); 
}

function titleCase(str){
     return this.replace(/\w\S*/g, function(txt){return txt.chartAt(0).toUpperCase} + txt.substr(1).toLowerCase();});
};

Everytime I use the => it tells me that I need esversion:6 in order to run it.

My question, what am I doing wrong, and what would be the most idiomatic way to go about doing this?

Pictures to prove I'm not crazy:

enter image description here

13aal
  • 1,634
  • 1
  • 21
  • 47

2 Answers2

1

To detail the issues with your existing solutions, they almost work but have the following problems:

function titleCase(str){
   // missing `s.`--------v    v---extra "t" 
   str.split(' ').map(s => chartAt(0).toUpperCase() + s.slice(1)).join(' '); 
//^---missing return statement |---missing toLowerCase() call---^
}

function titleCase(str) {
     // -----v--should be `str`
     return this.replace(/\w\S*/g, function(txt){
       // ------------v--extra "t" |----v--- extra "}"
       return txt.chartAt(0).toUpperCase} + txt.substr(1).toLowerCase();
       // ---missing `()` -------------^
     });
};

Here are the fixed versions:

function titleCase(str){
   return str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1).toLowerCase()).join(' ');
}

function titleCase(str) {
     return str.replace(/\w\S*/g, function(txt){
       return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
     });
}
1

You can change the function so instead of returning in the forEach loop it appends the result onto an existing variable to be returned at the end.

Get the character at the start of each array value, change it to uppercase and then add it to the rest of the value which has been converted to lowercase.

Example:

function titleCase(str){
    var arrayify = str.split(' ');
    var result = '';
    arrayify.forEach(function(item) {
        result += item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() + ' ';
    });
    return result.slice(0, -1); // remove last whitespace
}
spaceman
  • 1,147
  • 8
  • 15