New to Rust? Grab our free Rust for Beginners eBook Get it free →
How to Uppercase First Letter in JavaScript

The task is to uppercase a JavaScript string’s first letter without changing the suffix. First-letter capitalization changes the beginning to uppercase and combines it with the untouched remainder in a new string.
This article shows a JavaScript function for that change and explains when CSS can capitalize text for display without changing the source value.
TL;DR
Use charAt(0), toUpperCase(), and slice(1) to uppercase the first UTF-16 code unit while leaving the suffix as written.
- Check the input contract before calling string methods.
- Use code-point iteration when the first symbol may sit outside the basic multilingual plane.
- Use CSS when the change is presentation only, not a stored string transformation.
What Is First-Letter Capitalization?
First-letter capitalization changes the beginning of a string to uppercase and joins it to the untouched remainder. JavaScript strings are immutable, so methods such as toUpperCase() and slice() return text that you combine into a new string.
In JavaScript, charAt(0) reads one UTF-16 code unit at index zero. toUpperCase() converts that value, and slice(1) returns the string from index one onward. The index is zero-based, so index 0 is the first unit.
The operation does not lowercase the suffix. That distinction matters for input such as hELLO, which becomes HELLO rather than Hello. If your requirement is sentence case, lowercase the suffix explicitly and document that rule.
| Need | Approach | Effect |
|---|---|---|
| Change first unit in data | charAt, toUpperCase, slice | Returns a new string |
| Change first code point | String iteration or spread | Keeps a surrogate pair together |
| Change appearance only | CSS text-transform | Stored text stays unchanged |
How to Uppercase the First Letter Step by Step
A short function keeps the input rule beside the transformation. It accepts strings and returns a new value.
Step 1: Define the input contract
Decide whether the function accepts only strings or converts other values. This version throws a TypeError for non-string values, which prevents accidental conversions from hiding a caller bug.
Step 2: Uppercase the first unit and append the suffix
The function uses charAt(0) rather than bracket access. For an empty string, charAt returns an empty string, so the combined result remains empty instead of trying to uppercase undefined.
function capitalizeFirst(value) {
if (typeof value !== "string") {
throw new TypeError("Expected a string");
}
return value.charAt(0).toUpperCase() + value.slice(1);
}
console.log(capitalizeFirst("javascript"));
console.log(JSON.stringify(capitalizeFirst("")));
console.log(capitalizeFirst("hELLO"));
The exact output from node capitalize_demo.js is:
Javascript "" HELLO
I ran node capitalize_demo.js and got Javascript, an empty string, and HELLO. The result preserves the original suffix casing, while the empty input stays empty.

Step 3: Apply the function to a collection
When an array contains strings, map() returns a new array with the function applied to each entry. It does not mutate the original array. Keep input validation in the function so a non-string entry is reported rather than silently changed.
const names = ["ada", "grace"]; const capitalized = names.map(capitalizeFirst);
That array operation is different from capitalizing every word inside one string. For that task, define what counts as a word before splitting or matching text, since punctuation, apostrophes and language-specific rules affect the result.
Regex and replace() for the First Letter
A regular expression can find the first character and replace it with its uppercase form. This can be concise when the rule is “the first character in the string,” but regular expressions introduce a matching rule that should be understood before using them.
const capitalizeWithRegex = (value) => {
if (typeof value !== "string") throw new TypeError("Expected a string");
return value.replace(/^./, (character) => character.toUpperCase());
};
console.log(capitalizeWithRegex("javascript"));
console.log(JSON.stringify(capitalizeWithRegex("")));
console.log(capitalizeWithRegex("hELLO"));
Here the caret anchors the match at the start, and the dot matches one character under the regular expression’s default rules. replace() returns a new string. For an empty input there is no match, so the original empty string comes back unchanged.
The callback receives the matched character and returns its uppercase version. A callback avoids replacement-string metacharacters being interpreted as special replacement instructions. It also makes the conversion step visible to a reader reviewing the code.
Use this form when the matching rule is already expressed as a regular expression. For a small helper with no other matching logic, the charAt form can be clearer to scan because the selected unit and untouched suffix appear directly in the return expression.
A dot does not match every possible Unicode character as one unit. JavaScript regular expressions without Unicode-aware matching operate on UTF-16 code units for this match.
- Use the u flag when the matching rule must recognize a code point.
- Use grapheme segmentation when the requirement concerns a displayed character made of multiple code points.
The u flag changes how the expression handles code points. It does not make a grapheme cluster into one unit.
The direct charAt and slice form exposes the pieces of the result and keeps its empty-string behavior clear. The regex form can fit naturally when an existing function already performs a start-anchored replacement. Choose one style for the codebase rather than presenting the expression as a universal improvement.
ES6 Spread Syntax and join()
Spread syntax turns an iterable string into an array of Unicode code points, so it can keep a surrogate pair together while selecting the first item. This is useful when the first symbol may be outside the basic multilingual plane.
function capitalizeWithSpread(value) {
if (typeof value !== "string") throw new TypeError("Expected a string");
const [first, ...rest] = [...value];
return (first ?? "").toUpperCase() + rest.join("");
}
console.log(capitalizeWithSpread("javascript"));
console.log(capitalizeWithSpread("𐐶ello"));
The first array element is the first code point, and rest contains all remaining points. join(“”) puts the suffix back together without adding a separator. The nullish fallback handles an empty array, which is what spreading an empty string produces.
Spread syntax is readable for a short string helper, but it creates an array containing every code point in the input. For ordinary form labels and names this is rarely a concern. For very large strings or a hot path processing many values, the charAt and slice approach avoids building that intermediate array and may better express the intended code-unit operation.
Code-point iteration is not the same as grapheme segmentation. A visible character may combine a base letter with a combining mark, or include joiners and variation selectors. If the requirement is to uppercase the first displayed symbol while preserving its attached marks, segment the string into grapheme clusters first and test that behavior with the languages and scripts your application supports.
JavaScript’s spread syntax uses the string iterator, but it is not a universal fix for every language rule. Case conversion can change the number of code points in a result.
Locale-specific casing can differ from default conversion. Keep those requirements separate from selecting the first item.
Using CSS for Dynamic Content
CSS text-transform can style text that arrives dynamically, provided it is rendered in an element covered by the style. The source value remains unchanged, so CSS is suitable when capitalization is a presentation choice rather than a data requirement.
.display-name {
text-transform: capitalize;
}
When JavaScript inserts a new display name into an element with the display-name class, the browser applies the rule during rendering. No second capitalization pass is needed for each update. This works with fetched values and user-interface state in the same way as other text styling, as long as the correct class reaches the rendered element.
The CSS capitalize value is word-oriented, not a promise to uppercase only the first character of the whole string. It applies text presentation rules to word beginnings. It should not be used to rewrite a database field, construct an API payload, or guarantee the exact spelling of a person’s name.
A stable class applies its rule as content changes without a separate script pass. If a component replaces its class or renders text into a different element, the selector must match that rendered node.
Shadow roots have separate styling boundaries. Inspect the element and computed style when appearance does not change.
CSS transformations can affect what a user sees while leaving text extraction and application data with the original casing. That distinction matters for copied text, form submissions, accessibility review, and tests that inspect the DOM value. Choose CSS for visual presentation and JavaScript for a transformed string that downstream code must receive.
| Requirement | Use | Reason |
|---|---|---|
| Change a saved or submitted value | JavaScript string function | The returned string carries the casing |
| Style changing UI text | CSS text-transform | The rule follows the rendered element |
| Uppercase exactly one initial code point | Explicit JavaScript logic | The scope is narrower than CSS capitalize |
Edge Cases and Variations
Choose the implementation based on input shape and language requirements. The compact method is appropriate for ordinary strings whose initial character is one UTF-16 code unit.
| Input or requirement | What happens | Recommended handling |
|---|---|---|
| Empty string | charAt(0) returns empty string | Return the unchanged empty value |
| Number or null | Type guard rejects it | Validate or deliberately coerce at the boundary |
| Already uppercase first unit | Output remains unchanged | No special branch required |
| Mixed-case suffix | Suffix casing is preserved | Use toLowerCase() only if normalization is required |
| Astral first code point | charAt can isolate one half of a surrogate pair | Iterate code points instead |
| Locale-specific casing | Default uppercase rules may not match locale expectations | Use toLocaleUpperCase(locale) with the intended locale |
- For a displayed character made from multiple code points, segment grapheme clusters.
- For first-word-only behavior, define what counts as a word before transforming it.
Empty and non-string input
Using value[0].toUpperCase() without checking the string causes a common error. For an empty string, value[0] is undefined and calling toUpperCase() fails.
charAt(0) returns an empty string for an out-of-range position. The ordinary composition therefore returns the empty input unchanged.
Passing a number triggers TypeError: Expected a string. Convert at the boundary only when numeric text belongs in the function contract.
Unicode code points and grapheme clusters
JavaScript string indices count UTF-16 code units, not user-perceived characters. Some Unicode code points occupy two code units. Applying charAt(0) to one of those can separate the pair, so use the string iterator when the first code point may be outside the basic multilingual plane.
I compared the two approaches on a Deseret character: charAt left the first symbol unchanged, while code-point iteration returned its uppercase form. That probe supports using the iterator when astral letters are part of the input.
Code points still do not always match visible glyphs. A grapheme can contain multiple code points, such as a base letter followed by a combining mark. Applications that must edit the first displayed character should segment grapheme clusters with Intl.Segmenter and handle the cluster as a unit.
Locale and word-level casing
toUpperCase() applies default Unicode case conversion, not a locale selected for a particular user. Turkish dotted and dotless I are familiar examples where locale-specific behavior matters. When the application knows the user’s language, use toLocaleUpperCase() with an explicit locale and test the desired language examples.
Capitalizing the first letter of every word is a separate transformation. Splitting only on a literal space misses tabs and repeated whitespace. A regular expression needs a clear definition of word boundaries.
CSS text-transform can change display styling without rewriting data, while copied or submitted strings retain original casing.
For more string extraction examples, see removing characters from a JavaScript string. If leading or trailing whitespace changes which character should count as first, review JavaScript trim methods and choose whether trimming belongs in your data rule.
Choosing a Method for Your Input
Pick the method from the contract your caller needs: one initial code unit, one code point, word-level display styling, or a value that must be stored in transformed form. The methods overlap on simple Latin text, but their behavior differs at empty input, Unicode boundaries, and the point where the result is consumed.
| Method | Input unit or scope | Useful when | Watch for |
|---|---|---|---|
| charAt(0) + slice(1) | First UTF-16 code unit | A small transformation should be explicit | A surrogate pair may be split |
| replace(/^./, callback) | First regex match | The surrounding code already uses a start-anchored replacement | Dot and Unicode matching rules |
| Spread and join | First code point | A leading astral code point must remain intact | It allocates an array and does not segment graphemes |
| CSS capitalize | Rendered word beginnings | Appearance changes without changing application data | It is not a stored one-letter transformation |
For a stored value, keep the pure string function near the data boundary and call it once when the value is created or normalized. For a view-only label, a CSS class avoids changing the value that the application submits. That separation makes it possible for the interface to show a style while logs, payloads, and stored records retain their chosen data representation.
For form input, validation and transformation are separate decisions. A type check answers whether the function received a string. A content rule answers whether an empty string, whitespace-only value, or leading punctuation is acceptable.
Trimming silently inside a capitalization helper changes more than letter case, so do it only when it is part of the contract.
For a value with leading spaces, the first code unit is a space and capitalization leaves it untouched. If the requirement means the first non-whitespace character, trim or locate that character deliberately and preserve the surrounding whitespace according to the application’s needs. Trimming the entire input first can remove meaningful formatting, so test whether spaces at either end are significant.
Word capitalization introduces additional choices. A title may preserve acronyms or lowercase short prepositions. It may follow a house style guide.
Applying toUpperCase() to each word beginning does none of that editorial work. A blanket transformation can damage intended spellings in names. Keep general-purpose string helpers narrow.
Put domain rules in a separately named function.
A useful test set includes ordinary lowercase input, already-capitalized input, mixed-case suffixes, an empty value, leading whitespace, and a non-string argument if the function promises a type guard. Add locale and Unicode examples when the product accepts those languages. Each case should assert the exact expected output, not only that the result is truthy.
Choose based on the input unit and where the result goes. Does the first symbol need code-point handling, and does another part of the program need the transformed value? Those answers narrow the choice more than expression length.
Test the String Contract
A capitalization helper is easiest to maintain when its name and tests describe exactly which part of the input it changes.
- Check an empty string and verify it stays empty.
- Check an uppercase first character and verify it remains unchanged.
- Check a mixed-case suffix and verify the suffix is preserved.
- Check the chosen non-string policy, either a type error or documented conversion.
For the charAt version, charAt returns an empty string when the index is outside the input. The regex version has no match and returns the original value.
The spread version has no first array element and relies on its empty fallback. The outputs agree, though the implementations reach them differently.
Already-capitalized input should remain unchanged after another call. Mixed-case input checks a different promise: this helper changes one initial character, not the suffix. A name such as capitalizeFirstCodeUnit or capitalizeFirstCodePoint can make that scope clear.
Whitespace deserves an explicit expected result. A leading space is itself the first code unit, so the basic implementation returns the original string. Some interfaces want the first visible letter changed while retaining whitespace.
Others trim input before storing it. The test should encode the product rule instead of letting a utility decide silently.
Locale tests should use the locale parameter when that behavior is part of the contract. The default conversion and locale-sensitive conversion are different APIs with distinct expected results. Test the actual languages the product supports rather than assuming one example represents every alphabet.
When a helper is used on an array, map() is a useful way to produce a transformed array without changing the original. The callback receives each value, so a strict string-only helper will throw when any entry violates its contract. If invalid entries should be skipped or retained, that policy belongs in the array transformation and should be tested there.
Keep transformation and validation separate when they answer different questions. Validation can reject a blank field, enforce a maximum length, or check an allowed character set.
Capitalization changes case. A function that combines all these policies becomes harder to reuse because callers may want the casing behavior without the form-specific restrictions.
For a durable application rule, write down whether input is trimmed, whether suffix casing changes, which Unicode unit is processed, whether locale matters, and what happens for non-strings. That compact contract helps prevent an implementation chosen for a short example from silently becoming a broader promise.
A common extension is capitalizing every word rather than the first character of the whole string. That task needs a word-boundary rule, because punctuation and whitespace do not always divide words in the same way. A split on a space character, for instance, treats tabs differently and can preserve empty array items when spaces repeat.
A map-based approach makes the transformation sequence visible: split the input into chosen pieces, transform the beginning of each piece, then join the pieces with the intended separator. This can alter whitespace if the original separators are replaced during joining. If preserving exact spacing matters, match the words while retaining separators or use a parser designed for the text’s language.
A regular expression for title casing often looks compact but can hide its definition of a word. ASCII-oriented boundaries may not align with accented letters or scripts that do not use spaces between words. Test representative input before applying a general rule, and prefer domain-specific title casing where the output has editorial significance.
CSS capitalize also differs from a whole-string initial transformation. Its job is presentation across word beginnings, and its output is not a new JavaScript string. It is useful for dynamic labels because the browser applies the style when text is rendered, but it cannot prepare a canonical value for a request body or storage layer.
For dynamic data, keep the distinction between source and display clear. An API may provide lowercase text, the application may retain that source value, and a CSS rule may display it with capitalization. If another part of the program needs the transformed value, call a JavaScript function and pass the returned string there instead of relying on visual styling.
CSS selectors must continue to match after rendering updates. Frameworks may replace an element or class as state changes, so confirm the rendered node has the class and that its computed text-transform property is the expected value. A style that works on initial content can appear absent when a later render uses a different element or style scope.
Do not uppercase values as a substitute for escaping or sanitizing them. Capitalization changes case only and says nothing about whether text is safe to place into HTML, SQL, a shell command, or a URL. Keep security validation and encoding at the relevant output boundary.
For a reusable helper, document whether it handles only the first unit or a full code point, whether it changes the suffix, and what input types it accepts. A carefully named function limits surprises when the same transformation later appears in a form, a display component, and a data import path.
When comparing examples from tutorials, check what their term “first letter” means. A code-unit implementation may capitalize the first code unit, another may find the first non-space character, and a third may apply title casing to every word. These are distinct contracts even when a simple input produces the same visible result.
For a first non-whitespace rule, the function must find an index and preserve the prefix before that index. It should define which whitespace characters count and what an all-whitespace string returns. That behavior is not provided by charAt(0) + slice(1), because index zero remains the selected position regardless of what character it contains.
For locale-aware text, pass a known locale to the locale-sensitive casing method and verify the result against the user-facing requirement. Avoid relying on the machine’s ambient locale, which can differ between development, server execution, and a user’s browser. A stable rule makes generated values predictable across environments.
For text that users can edit, preserving the original value may be preferable to changing it automatically. A visual style can communicate a display convention without overwriting user-entered casing. If the application normalizes the saved value, explain that transformation and give users a way to retain intentional capitalization where names or identifiers are involved.
Conclusion
For a string whose first character uses one UTF-16 code unit, combine charAt(0).toUpperCase() with slice(1). Treat empty values, non-string inputs, Unicode code points and locale behavior as explicit requirements rather than hidden assumptions.
Use the MDN references for charAt(), slice(), and toUpperCase() when you need method details.
FAQ
These answers distinguish first-character conversion from related casing tasks.
How do I uppercase only the first letter in JavaScript?
Return str.charAt(0).toUpperCase() + str.slice(1) after confirming that str is a string.
Does JavaScript have a built-in capitalize method?
String has case-conversion methods such as toUpperCase(), but no method that capitalizes only the first letter of a string.
How do I capitalize the first letter of each word?
Apply a word-level transformation to each defined word boundary. Decide how punctuation, whitespace and locale rules should work before choosing split, map or a regular expression.
Will the charAt approach handle emoji or every Unicode character?
No. charAt reads one UTF-16 code unit. Use code-point iteration for astral code points, and grapheme segmentation when a displayed character can contain multiple code points.




