JavaScript capitalize first letter | Example code

  • by

You have to use charAt(), toUpperCase() and slice() method to capitalize first letter in JavaScript. The charAt() function returns the character at a given position in a string.

str.charAt(0).toUpperCase() + str.slice(1);

And toUpperCase() function converts all the characters of an input string to uppercase, where slices a given string from a specified “start” position until the specified “end” position.

JavaScript capitalize first letter

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    const str = 'abc efg';

    const res = str.charAt(0).toUpperCase() + str.slice(1);
    console.log(res);
  </script>
</body>
</html> 

Output:

JavaScript capitalize first letter

How do I make the first letter of a string uppercase in JavaScript?

Answer: "this is a test""This is a test"

The basic solution is:

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

console.log(capitalizeFirstLetter('foo')); // Foo

Do comment if you have any doubts or suggestions on this JS basic 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.