Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Title Case JavaScript

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.

like image 266
Kitty Avatar asked Apr 21 '18 01:04

Kitty


2 Answers

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.

like image 80
Jonathan Lam Avatar answered Oct 20 '22 07:10

Jonathan Lam


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(" ");
}
like image 22
Gokul Avatar answered Oct 20 '22 08:10

Gokul