How to Title Case a sentence in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

Title Case a sentence in javascript

It is nothing but converting first element of all the words in a sentence in to uppercase while the other elements remain in lowercase. The provided string(sentence) may contains a bunch of lowercase and uppercase elements. So we need an algorithm to Title Case the provided string.

Algorithm

  • Divide all the words in the sentence individually. This task can be achieved by using string.split() method.
  • Convert all the elements in each and every word in to lowercase using string.toLowerCase() method. 
  • Loop through first elements of all the words using for loop and convert them in to uppercase. After converting, concatenate them with the remaining elements of their respective word, leading to a original word with first element in upper case. 
  • Join all the words using String.join() with a space between them so as to convert it in to its original string but title cased.

Example

Live Demo

<html>
<body>
<script>
   function titleCase(string) {
      var sentence = string.toLowerCase().split(" ");
      for(var i = 0; i< sentence.length; i++){
         sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
      }
   document.write(sentence.join(" "));
   return sentence;
   }
   titleCase("tutorix is one of best e-platforms");
</script>
</body>
</html>

Output
Tutorix Is One Of Best E-platforms

raja
Published on 12-Jun-2019 10:34:02
Advertisements