6

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.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
Kitty
  • 137
  • 2
  • 8
  • 2
    one thing I wouldn't do is have `String` as the argument name - I mean, you can, but don't. .. the whole function is simply `const title_case = s => s.toLowerCase().split(' ').map(w => w[0].toUpperCase() + w.slice(1)).join(' ')` – Jaromanda X Apr 21 '18 at 01:48
  • Does this answer your question? [JavaScript titleCase function without regex](https://stackoverflow.com/questions/33766968/javascript-titlecase-function-without-regex) – AncientSwordRage Nov 30 '21 at 17:27

2 Answers2

6

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.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
  • Thank you so much! This put me on the right track. I really appreciate you also explaining further on concatenation and the logic behind the coding. This was fantastic help. Thank you! – Kitty Apr 21 '18 at 01:38
  • @Val7x I'm glad the explanation helped! – Jonathan Lam Apr 21 '18 at 01:40
1

Use the below functions to just capitalise a sentence or title case a sentence.

console.log(capitalizeFirstLetter("THIS IS A SENTENCE")); //converts a sentence to capitalise. 

console.log(titleCase("THIS IS A SENTENCE")); //converts a sentence to titlecase. 

function capitalizeFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1).toLowerCase();
}

function titleCase(string) {
    return string.split(" ").map(x => capitalizeFirstLetter(x)).join(" ");
}
Gokul
  • 117
  • 1
  • 4