Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-23 11:30:56
Original
370 people have browsed it

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"));
Copy after login

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(' '); 
}
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!