In English, it’s essential to capitalize the first letter of a sentence. JavaScript has built-in methods to help us with this.
In this article we will look at three different ways to check if the first letter of a string is upper case and how to capitalize it.
We can check if the first of a letter a string is upper case in a few ways. Let’s take a look at some popular ones.
This is a built-in string method that returns the invoked string with only upper case characters:
function startsWithCapital(word){
return word.charAt(0) === word.charAt(0).toUpperCase()
}
console.log(startsWithCapital("Hello")) // true
console.log(startsWithCapital("hello")) // false
Here, we’re making a single character string consisting of only the first letter/character of the provided string and comparing it to its upper case version. If they match, the original letter is uppercase.
Note: string.charAt(index)
is preferred over string[index]
(bracket notation). This is because "".charAt(0)
returns an empty string whereas ""[0]
returns undefined
.
#javascript