Title Case JavaScript

Kitty picture Kitty · Apr 21, 2018 · Viewed 7.6k times · Source

I am trying to create a function in which after toLowerCase() input, will then capitalize the first letter in each element of an array.

function title_case ( String ) {
    var result = "";
    var text = String.toLowerCase().split(" ");
    for (var i = 0; i < text.length; i++) {
      var c = text[i].charAt(0).toUpperCase();
      result = result + c;
    }
    return result;
  }

Input:

document.write( title_case( "a kitty PUrrs") );

The resulting output of the current code is AKP. I'm trying to figure out a way to delete lowercase character with charAt(1) and then join() for the output if possible. Am I on the right track? I know there are simpler methods, but I'm trying to learn something along these lines.

Answer

Jonathan Lam picture Jonathan Lam · Apr 21, 2018

Instead of deleting the first character, you can make a substring of the rest of the string after the first character. I.e.:

result = result + c + text[i].substring(1, text[i].length()-1) + " ";

The text[i].substring(1, text[i].length()-1) gets the part of the word from the second character to the end of the word (kind of like "deleting" the first character).

And you don't need a join() function for strings, just + for concatenation. The " " at the end separates the words with spaces. At the end of the function, you can return result.trim() to get rid of the last space.