NeuroAgent

JavaScript Capitalize First Letter: Best Method Explained

Master JavaScript string capitalization with our comprehensive guide. Learn the most efficient method to capitalize the first letter while preserving the rest of the string.

Question

How do I capitalize the first letter of a string in JavaScript while keeping the rest of the string unchanged?

I need to make only the first character of a string uppercase if it’s a letter, without changing the case of any other characters. For example:

  • “this is a test” → “This is a test”
  • “the Eiffel Tower” → “The Eiffel Tower”
  • “/index.html” → “/index.html”

What’s the most efficient way to accomplish this in JavaScript?

NeuroAgent

The most efficient way to capitalize the first letter of a string in JavaScript while keeping the rest unchanged is using str.charAt(0).toUpperCase() + str.slice(1). This method reliably accesses the first character, converts it to uppercase, and combines it with the rest of the string starting from the second character, leaving all other characters unchanged.

Contents


Common Methods to Capitalize First Letter

Method 1: charAt() + slice() - Most Recommended

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

This is the most widely used and recommended approach according to multiple sources. The charAt() method safely accesses the first character, toUpperCase() converts it to uppercase, and slice() extracts the rest of the string.

Examples:

javascript
capitalizeFirstLetter("this is a test"); // "This is a test"
capitalizeFirstLetter("the Eiffel Tower"); // "The Eiffel Tower"
capitalizeFirstLetter("/index.html"); // "/index.html"

Method 2: ES6 Destructuring Assignment

javascript
const capitalize = ([first, ...rest]) => first.toUpperCase() + rest.join('');

This modern ES6 approach uses array destructuring to separate the first character from the rest of the string. While elegant, it’s not the most performant option as noted in the research findings.

Method 3: Regular Expression

javascript
function capitalizeWithRegex(str) {
  return str.replace(/^./, char => char.toUpperCase());
}

The regular expression /^./ matches the first character at the beginning of the string. This method is functional but significantly slower than the charAt() approach.

Method 4: String Indexing with substring()

javascript
function capitalizeWithSubstring(str) {
  return str[0].toUpperCase() + str.substring(1);
}

This method uses string indexing and the substring() method. Note that str[0] returns undefined for empty strings, requiring additional error handling.


Performance Comparison

Based on benchmark tests from the research findings, here’s the performance ranking from fastest to slowest:

  1. charAt(0).toUpperCase() + slice(1) - Fastest (~2,000,000 operations/sec)
  2. String indexing with substring(1) - Slightly slower than slice, but still very fast
  3. ES6 destructuring - Significantly slower
  4. Regular expression method - “Like a snail compared to the others”

Key Insight: The charAt() approach is the most performant because it doesn’t involve creating regex objects or using complex string operations. According to Stack Overflow, substring(1) is often slightly faster than slice(1), but the difference is minuscule in modern JavaScript engines.


Edge Cases and Error Handling

The basic charAt() approach handles most edge cases well, but here are some considerations:

Empty Strings

javascript
capitalizeFirstLetter(""); // "" (returns empty string)

Non-letter Characters

The method works correctly with non-letter characters:

javascript
capitalizeFirstLetter("123abc"); // "123abc"
capitalizeFirstLetter("!hello"); // "!hello"

Unicode Characters

For proper Unicode support, consider this enhanced version:

javascript
function capitalizeFirstLetterUnicode(str) {
  if (!str) return str;
  const firstChar = str.charAt(0);
  const rest = str.substring(String.fromCodePoint(firstChar).length);
  return firstChar.toUpperCase() + rest;
}

Complete Implementation Examples

Basic Implementation

javascript
/**
 * Capitalizes the first letter of a string while keeping the rest unchanged
 * @param {string} str - The input string
 * @returns {string} The string with first letter capitalized
 */
function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

Implementation with Error Handling

javascript
function safeCapitalizeFirstLetter(str) {
  if (typeof str !== 'string' || str.length === 0) {
    return str;
  }
  return str.charAt(0).toUpperCase() + str.slice(1);
}

Implementation for Multiple Words (Title Case)

javascript
function capitalizeWords(str) {
  return str.split(' ').map(word => 
    word.charAt(0).toUpperCase() + word.slice(1)
  ).join(' ');
}

When to Use Each Method

Use charAt() + slice() when:

  • You need maximum performance
  • You’re working in performance-critical code (loops, frequent operations)
  • You prefer straightforward, readable code
  • You need broad browser compatibility

Use ES6 Destructuring when:

  • You’re using modern JavaScript (ES6+)
  • Code readability and elegance are prioritized over performance
  • You’re working in environments where performance isn’t critical

Use Regular Expressions when:

  • You need to match more complex patterns
  • You’re already using regex for other string operations
  • Performance is not a concern

Use String Indexing when:

  • You’re certain the input string is never empty
  • You prefer concise syntax and are aware of the limitations

Conclusion

For capitalizing the first letter of a string in JavaScript while keeping the rest unchanged, str.charAt(0).toUpperCase() + str.slice(1) is the most efficient and recommended method. It provides the best balance of performance, readability, and reliability across different use cases.

Key recommendations:

  1. Always use the charAt() approach for optimal performance
  2. Consider edge cases like empty strings in production code
  3. Choose alternative methods only when specific requirements justify the performance trade-off
  4. For title case operations (capitalizing multiple words), extend the basic approach with array mapping

This method will work efficiently for all the examples provided: “this is a test” → “This is a test”, “the Eiffel Tower” → “The Eiffel Tower”, and “/index.html” → “/index.html”.

Sources

  1. JavaScript Capitalize First Letter - Flexiple
  2. How do I make the first letter of a string uppercase in JavaScript? - Stack Overflow
  3. How to capitalize the first letter in JavaScript? - CoreUI
  4. JavaScript - How to Make First Letter of a String Uppercase? - GeeksforGeeks
  5. Capitalize the First Letter of a String in JavaScript - Mastering JS
  6. How to capitalize first letter in JavaScript - Weekend Projects