Skip to content

JavaScript capitalize first letter of each word | Example code

  • by

Use the toUpperCase() method to capitalize the first letter of each word in JavaScript. This method will uppercase all words but you want only first letter. Use the first index of every word and capitalize it using toUpperCase() method.

const site = "eyeHunts";
var res = site[0].toUpperCase() + site.substring(1);
console.log(res)

JavaScript capitalizes the first letter of each word

A simple example code capitalizes the first letter of each word from a string. First, split the sentence into an array and Iterate over each word then capitalize the first letter of each word. And lastly, Join the words.

<!DOCTYPE html>
<html>
<body>

<script>
   const msg = "eyeHunts tutorial is an awesome";
   const words = msg.split(" ");

   for (let i = 0; i < words.length; i++) {
    words[i] = words[i][0].toUpperCase() + words[i].substr(1);
  }

  var res = words.join(" ");

  console.log(res)

</script>

</body>
</html> 

Output:

JavaScript capitalize first letter of each word

More example

There are multiple ways of solving the same problem. So let’s see another approach.

word[0].toUpperCase(): It’s the first capital letter and word.substr(1) the whole remaining word except the first letter which has been capitalized. This is a document for how substr works.

function toUpper(str) {
return str
    .toLowerCase()
    .split(' ')
    .map(function(word) {
        console.log("First capital letter: "+word[0]);
        console.log("remain letters: "+ word.substr(1));
        return word[0].toUpperCase() + word.substr(1);
    })
    .join(' ');
 }
 console.log(toUpper("hello friend"))

Output: Hello Friend

Using the map function

const mySentence = "Hello is an awesome resource";
const words = mySentence.split(" ");

words.map((word) => { 
    return word[0].toUpperCase() + word.substring(1); 
}).join(" ");

one-liner with RegEx

const mySentence = "Hello is an awesome resource";

const finalSentence = mySentence.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase());
  • ^ matches the beginning of the string.
  • \w matches any word character.
  • {1} takes only the first character.
  • Thus, ^\w{1} matches the first letter of the word.
  • | works like the boolean OR. It matches the expression after and before the |.
  • \s+ matches any amount of whitespace between the words (for example spaces, tabs, or line breaks).

Do comment if you have any doubts or suggestions on this JS capitalize topic,

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading