Sometimes, we need to get the first character of a JavaScript string in our code.
In this article, we’ll look at how to get the first character of a JavaScript string.
String.prototype.charAt
The chartAt
method that comes with JavaScript strings lets us get a character from a string by its index.
To get the first character, we pass in 0 to the method.
For instance, we can write:
const first = 'abc'.charAt(0)
console.log(first)
Therefore, first
is 'a'
.
String.prototype.substring
The substring
method lets us get a substring from a string given the start and end index.
The character at the starting index is included.
But the character at the ending index isn’t.
So we can write:
const first = 'abc'.substring(0, 1)
console.log(first)
And we get the same result.
String.prototype.slice
Like the substring
method, the slice
method also lets us get a substring with the start and end indexes.
Like substring
, the character at the starting index is included.
But the character at the ending index isn’t.
For instance, we can write:
const first = 'abc'.slice(0, 1)
console.log(first)
And we get the same results as the other examples.
Square Brackets
We can pass in the index of the first character into square brackets as we do with charAt
.
For example, we can write:
const first = 'abc'[0]
console.log(first)
Then we get the same result as with charAt
.
Conclusion
There are several ways we can get the first character of a string with JavaScript.
We can do it either with square brackets or string methods.