4

I'm currently trying to figure out how to capitalize the first letter of each word in a string (all other letters in the word lowercase). For example: "Coding Can Be Confusing"

Here's what I have so far. I know I am definitely missing code, I'm just not sure what should come next. I'm also not sure if what do I have is even correct. Any help would be greatly appreciated.

function titleCase(str) {
  var words = str.toLowerCase.split(' ');

  for(i = 0; i < words.length; i++) {
    var firstLetter = words[i].charAt(0).toUpperCase;
  }

  return words.join(' ');
}

titleCase("I'm a little tea pot");
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
shy0ctopus
  • 61
  • 5

4 Answers4

3

You can use map() and substring() and do something like this

function titleCase(str) {
  return str.toLowerCase().split(' ').map(function(v) {
    return v.substring(0, 1).toUpperCase() + v.substring(1)
  }).join(' ');
}
document.write(titleCase("I'm a little tea pot"));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

Try this code:

var str = "this is sample text";
console.log(toTitleCase(str));

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

JsFiddle

Apb
  • 979
  • 1
  • 8
  • 25
0

use below code for ucword

        function titleCase(str) {
            return (str + '')
                .replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
                    return $1.toUpperCase();
                });
        }
    
        var data = titleCase("I'm a little tea pot");
        document.write(data);
    
Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
0

How about this

var text = "I'm a little tea pot"

text = text.split(" ")
//["I'm", "a", "little", "tea", "pot"]

final = $.map(text, function(val,i){
 return val = val[0].toUpperCase() + val.slice(1,val.length)
})
// ["I'm", "A", "Little", "Tea", "Pot"]

final.join(" ")
// "I'm A Little Tea Pot"

So the function would be

function titleCase(str) {
    return text.split(" ").map(function(val,i){
        return val[0].toUpperCase() + val.slice(1,val.length)
    }).join(" ")
}

var text = "I'm a little tea pot"
console.log(titleCase(text))
//"I'm A Little Tea Pot"
ashishmohite
  • 1,120
  • 6
  • 14