Question

How do you capitalize the first letter in JavaScript?

Answer and Explanation

Capitalizing the first letter of a string is a common task in JavaScript. There are several ways to achieve this, and here's a breakdown of the most efficient and readable methods:

Method 1: Using String methods `charAt()`, `toUpperCase()` and `slice()`

This is a clear and commonly used approach.

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

const myString = "hello world";
const capitalizedString = capitalizeFirstLetter(myString);
console.log(capitalizedString); // Output: "Hello world"

- `string.charAt(0)` gets the first character of the string.

- `.toUpperCase()` converts that character to uppercase.

- `string.slice(1)` returns the rest of the string, starting from the second character (index 1).

- Finally, we combine the uppercase first character with the rest of the string.

Method 2: Using bracket notation and template literals:

This method is a variation of the first one using bracket notation for character access.

function capitalizeFirstLetter(string) {
  return `${string[0].toUpperCase()}${string.slice(1)}`;
}

const myString = "javascript";
const capitalizedString = capitalizeFirstLetter(myString);
console.log(capitalizedString); // Output: "Javascript"

- `string[0]` accesses the first character of the string.

- Template literals (backticks) are used for more concise string concatenation.

Method 3: Using Regular Expressions:

You could also use regex for this, though it's often overkill for such a simple task.

function capitalizeFirstLetter(string) {
  return string.replace(/^./, str => str.toUpperCase());
}

const myString = "lowercase";
const capitalizedString = capitalizeFirstLetter(myString);
console.log(capitalizedString); // Output: "Lowercase"

- The regex `^.` matches the first character of the string.

- The `replace()` function with a callback function converts the matched character to uppercase.

Best practice

For most cases, Method 1 (using `charAt()`, `toUpperCase()` and `slice()`) is the most readable and efficient way to capitalize the first letter of a string in JavaScript. It's clear, easy to understand, and performs well for most use cases. If you are already using a framework and the method from framework is available for this, it would be the best to use the method from framework.

More questions

Dashboard
Image ID
Talk to AI
AI Photos
Get App