"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Capitalize the First Letter of Each Word in a String with JavaScript?

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

Published on 2024-11-07
Browse:845

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

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

In JavaScript, capitalizing the first letter of each word in a string can be achieved through several methods. One common approach involves using a function that transforms the given string into title case.

Let's explore a code example that demonstrates this technique:

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

In this function, the input string 'str' is first converted to lowercase using 'toLowerCase()'. Then, the string is split into an array of words using 'split(" ")'. For each word in the array, the first character is capitalized using 'charAt(0).toUpperCase()' and appended to the rest of the word using 'substring(1)'.

The modified array of capitalized words is then joined back into a string using 'join(" ")' and returned as the output, which will be displayed in title case.

Release Statement This article is reprinted at: 1729652296 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3