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?
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
- Performance Comparison
- Edge Cases and Error Handling
- Complete Implementation Examples
- When to Use Each Method
Common Methods to Capitalize First Letter
Method 1: charAt() + slice() - Most Recommended
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:
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
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
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()
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:
charAt(0).toUpperCase() + slice(1)- Fastest (~2,000,000 operations/sec)- String indexing with
substring(1)- Slightly slower than slice, but still very fast - ES6 destructuring - Significantly slower
- 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 thanslice(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
capitalizeFirstLetter(""); // "" (returns empty string)
Non-letter Characters
The method works correctly with non-letter characters:
capitalizeFirstLetter("123abc"); // "123abc"
capitalizeFirstLetter("!hello"); // "!hello"
Unicode Characters
For proper Unicode support, consider this enhanced version:
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
/**
* 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
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)
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:
- Always use the
charAt()approach for optimal performance - Consider edge cases like empty strings in production code
- Choose alternative methods only when specific requirements justify the performance trade-off
- 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
- JavaScript Capitalize First Letter - Flexiple
- How do I make the first letter of a string uppercase in JavaScript? - Stack Overflow
- How to capitalize the first letter in JavaScript? - CoreUI
- JavaScript - How to Make First Letter of a String Uppercase? - GeeksforGeeks
- Capitalize the First Letter of a String in JavaScript - Mastering JS
- How to capitalize first letter in JavaScript - Weekend Projects