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

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

Linda Hamilton
Release: 2024-10-23 12:52:01
Original
590 people have browsed it

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

Capitalizing First Letter of Each Word in a String Using JavaScript

Question:

I'm struggling to capitalize the first letter of each word in a string. Specifically, my function converts "I'm a little tea pot" to "i'm a little tea pot" instead of the desired output, "I'm A Little Tea Pot." Here's my JavaScript code:

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

Answer:

The error in your code lies in not assigning the modified word back to the array correctly. To resolve this issue, modify your code as follows:

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // No need to check if i is larger than splitStr length, as your for loop does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Return the joined string directly
   return splitStr.join(' '); 
}

document.write(titleCase("I'm a little tea pot"));
Copy after login

Changes made:

  • Removed the unnecessary length check in the if statement.
  • Assigned the capitalized word back to the array (e.g., splitStr[i] = ...) instead of just calling charAt(0).toUpperCase().
  • Returned splitStr.join(' ') directly instead of first reassigning it to str.

The above is the detailed content of How to Capitalize the First Letter of Each Word in a String in 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!