Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How do I make the first letter of a string uppercase in JavaScript?

How do I make the first character of a string uppercase if it's a letter, but not change the case of any of the other letters?

For example:

  • "this is a test""This is a test"
  • "the Eiffel Tower""The Eiffel Tower"
  • "/index.html""/index.html"

Answer*

Draft saved
Draft discarded
Cancel
9
  • 7
    Here's this solution in TypeScript, where the type returned is the capitalized word, rather than string: const capitalize = <T extends string>(s: T) => (s[0].toUpperCase() + s.slice(1)) as Capitalize<typeof s>; Commented Mar 27, 2023 at 17:56
  • 5
    This is mentioned in answers below, but worth pointing out here: this answer does not work for all Unicode text. Passing "𐐨𐑍𐑏" to this function returns the same string, but it should return "𐐀𐑍𐑏". That's because charAt splits at UTF16 code units. There are characters with case-folding definitions in the SMP that are encoded with two UTF16 code units. While simple, this shouldn't be used. Commented Sep 28, 2023 at 7:34
  • 5
    You don't even have to reach for rare languages to break this. Unicode ligature characters break this as well: "flat" is returned as "FLat". Commented Sep 28, 2023 at 7:42
  • 1
    @Disorder it's not a launguage feature. Dan just defines the function as a type-safe one-liner ... not super useful? Commented May 3, 2024 at 8:58
  • 1
    @mhvelplund just mentioned that Capitalize type in TS is a key for typing, and it's out of the box. What's wrong? typescriptlang.org/docs/handbook/… Commented Aug 25, 2024 at 0:09

lang-js

AltStyle によって変換されたページ (->オリジナル) /