Title Case JavaScript
Asked Answered
C

2

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.

Clammy answered 21/4, 2018 at 1:19 Comment(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(' ')World
Does this answer your question? JavaScript titleCase function without regexImprovident
F
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.

Fca answered 21/4, 2018 at 1:24 Comment(2)
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!Clammy
@Val7x I'm glad the explanation helped!Fca
I
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(" ");
}
Irrelative answered 14/11, 2018 at 14:27 Comment(1)
This would blow up when passed an empty string.Starknaked

© 2022 - 2024 — McMap. All rights reserved.