Title Case A Sentence JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say we are required to write a function that accepts a string and capitalizes the first letter of every word in that string and changes the case of all the remaining letters to lowercase.

For example, if the input string is −

hello world coding is very interesting

The output should be −

Hello World Coding Is Very Interesting

Let’s define a function capitaliseTitle() that takes in a string and capitalises the first letter of each word and returns the string −

Example

let str = 'hello world coding is very interesting';
const capitaliseTitle = (str) => {
   const string = str
   .toLowerCase()
   .split(" ")
   .map(word => {
      return word[0]
      .toUpperCase() + word.substr(1, word.length);
   })
   .join(" ");
   return string;
}
console.log(capitaliseTitle(str));

Output

The console output will be −

Hello World Coding Is Very Interesting
raja
Published on 18-Aug-2020 07:41:02
Advertisements