Skip to content

JavaScript capitalize first letter | Example code

  • by

You have to use charAt(), toUpperCase(), and slice() method to capitalize the 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.

Using String Methods:

<!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

Using ES6 Arrow Function and Template Literals:

You can also use ES6 features like arrow functions and template literals for a concise solution:

const capitalizeFirstLetter = (inputString) =>
  `${inputString.charAt(0).toUpperCase()}${inputString.slice(1)}`;

const originalString = "hello world";
const capitalizedString = capitalizeFirstLetter(originalString);
console.log(capitalizedString); // "Hello world"

Using Regular Expression:

Another way to capitalize the first letter is by using a regular expression:

function capitalizeFirstLetter(inputString) {
  return inputString.replace(/^\w/, (char) => char.toUpperCase());
}

const originalString = "hello world";
const capitalizedString = capitalizeFirstLetter(originalString);
console.log(capitalizedString); // "Hello world"

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

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

Discover more from Tutorial

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

Continue reading