Man in a hood on the background of green letters (matrix). On the back there is an inscription: "JavaScript Capitalize First Letter"

Get and capitalize the first letter of a string in JavaScript

How to capitalize the first letter of a string in JavaScript?

To capitalize the first character of a string in JavaScript while properly handling Unicode characters, you can use the String.prototype.charAt(), String.fromCodePoint() and String.prototype.substring() methods. This ensures that the first character is transformed to uppercase while the rest of the string remains unchanged, accommodating various Unicode character sets effectively, specifically surrogate pairs.

Surrogate pairs are crucial in Unicode because they allow the encoding of characters that fall outside the Basic Multilingual Plane (BMP), which includes code points above U+FFFF. In UTF-16 encoding, these characters are represented using two 16-bit code units: a high-surrogate and a low-surrogate. This mechanism is essential for supporting a wide range of characters, including many emojis and rare scripts, ensuring that applications can display and manipulate all Unicode characters effectively.

Without surrogate pairs, many characters would be inaccessible, limiting the representation of global languages and symbols in digital formats. For example, the character for the “grinning face with smiling eyes” emoji (😄) has a code point of U+1F604. In UTF-16, this is represented as the surrogate pair 0xD83D and 0xDE04.

Continue reading “Get and capitalize the first letter of a string in JavaScript”