0

What to do - Capitalize the first letter of the words in a sentence.

So, I solved it and was wondering is there any way to do it without making it an array with .split().

What I tried without turning it into a array -

The logic - First, turn everything into lowercase. Then scan the sentence with a for loop, if you find a space, capitalize the next character.

function titleCase(str) {
  str = str.toLowerCase();
  for(i=0;i<str.length;i++) {
    if(str[i]===" ") {
      str = str.charAt[i+1].toUpperCase();
      return str;
    }
  }
}
titleCase("I'm a little tea pot", "");

That code doesn't even run.

Dave
  • 10,748
  • 3
  • 43
  • 54
Lavios
  • 1,169
  • 10
  • 22
  • 7
    See [this](http://stackoverflow.com/questions/2332811/capitalize-words-in-string) question. – Vidul Sep 18 '15 at 18:37
  • and this one: http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript – jsxt Sep 18 '15 at 18:40
  • @jsxt that's not the same thing – CupawnTae Sep 18 '15 at 18:43
  • You might want to make check if you are reaching the last char of the array and then breaking the array by trying to reference the index outside of the scope: charAt[i+1]. if the array has 10 chars, and the i is at 9, then by reference i+1 you are trying to access index 10 which will through an error and stop the script, maybe this is why the code doesn't work. – Mohammed Joraid Sep 18 '15 at 18:46
  • if(str[i]===" ") { is not correct it should be if(str.charAt[i]==" ") – syarul Sep 18 '15 at 20:12
  • @ВидулПетров That answer only capitalizes the first letter of the first word, not first letter of all the words in the sentence. – Lavios Sep 18 '15 at 20:15
  • 1
    @Lavios Think again: `s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );` – Vidul Sep 18 '15 at 20:18
  • Yup. You're correct! I had opened too many tabs, before i saw your answer and there was a similar looking code and i used that instead of this. :) – Lavios Sep 18 '15 at 20:38
  • 1
    check this for the solution, if you want to do without regex https://jsfiddle.net/y5bcx9zx/ – syarul Sep 18 '15 at 21:03
  • @syarul Thanks! That helped – Lavios Sep 20 '15 at 12:05

2 Answers2

0

I just used split() and replace to do that. You can have a look at my code.

function titleCase (str)
{
    str = str.split(' ');
    for(var i=0;i<str.length;i++)
    {
        str[i] = str[i].replace(str[i][0],str[i][0].toUpperCase())
    }
    return str.join(' ');
}

var mainString ="i am strong!";
titleCase(mainString);
Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47
0

Here is one using replace + with a regex:

/**
 * @summary Uppercase the first letter in a string.
 * @returns {string}
 */
function uppercaseFirstLetters(string) {
    return string.replace(/[a-zA-Z]*/g, function(match) {
        return match.charAt(0).toUpperCase() + match.substr(1).toLowerCase();
    })
}
elad.chen
  • 2,375
  • 5
  • 25
  • 37