1

I am trying to use javascript to capitalize the words of a sentence. For example

var input = "I am not bad with javascript."
var output = "I Am Not Bad With Javascript."

I have the following codes and I can't figure out why my replace did not work.. Thank You

var loop = function(collection, callback){
    // ultimate side-effects function
    for (var i = 0; i < collection.length; i++){
      callback(collection[i]);
    }
};

    var capitalizeFirstLetters = function(string) {
      // have a new string
      // split the string into substring
      // use the loop function to find the "space"and CAP letter after 
      var newString = [];
      var subString = string.split(' ');
      loop(subString, function(word){
        subString.replace(word[0], word[0].toUpperCase());
        return newString.push(subString);
      })
      return newString.join(' ');
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 3
    Fun fact, you can do this in CSS with `text-transform: capitalize;`. I know yours is a JavaScript-specific question, but isn't it nice to know you sometimes don't need to write string manipulation functions? – aardrian Jul 06 '16 at 20:43
  • If you're using Lodash, you could use [this](http://stackoverflow.com/a/38084493/5743988). The string format you're referring to is called "title case" or "start case" – 4castle Jul 06 '16 at 20:44

2 Answers2

0

Here this should work

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

document.write(titleCase("I'm a little tea pot"));
Pieter de Vries
  • 825
  • 7
  • 18
0

You could try something like this:

var input = "I am not bad with javascript."
input = input.split(" ")
             .map(function(item){
                 return item[0].toUpper()+item.slice(1);
             })
             .join(" ");

var input = "I am not bad with javascript."
input = input.split(" ")
             .map(function(item){
                 return item[0].toUpperCase()+item.slice(1);
             }).join(" ");
alert(input);
Christos
  • 53,228
  • 8
  • 76
  • 108