Home  >  Article  >  Web Front-end  >  How to Capitalize the First Letter of Each Word in a String Using JavaScript?

How to Capitalize the First Letter of Each Word in a String Using JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 11:30:56371browse

How to Capitalize the First Letter of Each Word in a String Using JavaScript?

Capitalizing the First Letter of Each Word in a String Using JavaScript

In the pursuit of converting a string into title case, a challenge may arise where the first letter of each word remains lowercase. This article tackles this problem and provides a comprehensive solution using JavaScript.

Let us consider the following example:

function titleCase(str) {
  var splitStr = str.toLowerCase().split(" ");

  for (var i = 0; i < splitStr.length; i++) {
    if (splitStr.length[i] < splitStr.length) {
      splitStr[i].charAt(0).toUpperCase();
    }

    str = splitStr.join(" ");
  }

  return str;
}

console.log(titleCase("I'm a little tea pot"));

When executed, this code fails to convert the string to title case and returns "i'm a little tea pot" instead of "I'm A Little Tea Pot."

The underlying issue lies in the incorrect assignment of changes to the splitStr array. To rectify this, we need to assign the uppercase letter back to the array:

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   return splitStr.join(' '); 
}

This modification ensures that the first letter of each word is converted to uppercase within the splitStr array. Finally, we can directly return the joined string without the need for additional variable assignment.

The above is the detailed content of How to Capitalize the First Letter of Each Word in a String Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn