Home  >  Article  >  Web Front-end  >  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?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 11:38:18535browse

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:

<code class="js">function titleCase(str) {
  var splitStr = str.toLowerCase().split(" ");
  for (var i = 0; i < splitStr.length; i++) {
    splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);  
  }
  return splitStr.join(" "); 
}</code>

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.

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