Borislav Hadzhiev
Sat Mar 05 2022·2 min read
Photo by Greg Raines
To capitalize the first letter of a string in TypeScript:
charAt()
method to get the first letter of the string.toUpperCase()
method on the letter.slice()
method to get the rest of the string.const str = 'hello world'; // ✅ Capitalize first letter const result1 = str.charAt(0).toUpperCase() + str.slice(1); console.log(result1); // 👉️ "Hello world" // ✅ Capitalize first letter and lowercase rest const result2 = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); console.log(result2); // 👉️ "Hello world"
The first example in the code snippet converts the first letter of the string to uppercase and leaves the rest as is.
The second example, capitalizes the first letter and converts the rest to lowercase.
The only parameter we passed to the String.charAt method is the index of the character we want to get.
0
, and the index of the last - string.length - 1
.Then we used the
String.toUpperCase()
method to uppercase the character at position 0
.
We used the addition (+) operator to concatenate the first character with the rest of the string.
The only parameter we passed to the String.slice method is the start index - the index of the first character to be included in the new string.
Note that the type of the result
variable is string
. If used on an empty
string, this solution would return an empty string back and not throw an error.
const str = ''; // ✅ Capitalize first letter const result1 = str.charAt(0).toUpperCase() + str.slice(1); console.log(result1); // 👉️ "" // ✅ Capitalize first letter lowercase rest const result2 = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); console.log(result2); // 👉️ ""
charAt
and slice
methods return an empty string when accessed on an index out of bounds.We intentionally did not use bracket []
notation to access the first character
in the string, because it returns undefined
when passed an index that does not
exist in the string.
const str = ''; // 👇️ const r: string const result = str[100]; console.log(result); // 👉️ undefined // ⛔️ Error: cannot read property 'toUpperCase' // of undefined result.toUpperCase();
Even though the type of the result
variable is string
in the example above,
it stores a value of undefined
, so trying to call an method on an undefined
value would cause a runtime error.
toUpperCase
on is a string
.The charAt
method returns an empty string even when passed an index that
doesn't exist in the string.