There are multiple ways to get the first character of a string in JavaScript. You can use the charAt()
, substring()
, slice()
, at()
, or bracket notation property access to get the first character in a string.
Get the first character of a string using charAt()
method
To get the first character of a string, you can call the charAt()
method on the string, passing it 0
as the index of the character. This method returns a new string containing the character at the specified index.
const str = 'Protips'
const firstChar = str.charAt(0)
console.log(firstChar) // P
The charAt()
method returns the character of a string at the specified index.
If you provide an index that does not exist in the string, the charAt()
method returns an empty string:
const str = 'Protips'
const firstChar = str.charAt(9)
console.log(firstChar) // ""
String indexes are zero-based in JavaScript. The first character has an index of
0
, and the last has an index ofstr.length - 1
.
Get the first character of a string using bracket notation
You can also use the bracket notation ([]
) to get the first character of a string:
const str = 'Protips'
const firstChar = str[0]
console.log(firstChar) // P
Unlike charAt()
, the bracket notation returns undefined
if the given index does not exist, as shown below:
const str = 'Protips'
const firstChar = str[9]
console.log(firstChar) // undefined
Get the first character of a string using substring()
method
To get the first character of the string, call the substring()
on the string, and pass 0
and 1
as start and end indexes:
const str = 'Protips'
const firstChar = str.substring(0, 1)
console.log(firstChar) // P
The substring()
method extracts characters between the start and end indexes from a string and returns the substring. The substring between the indexes 0
and 1
is a substring containing only the first string character.
Get the first character of a string using slice()
method
To get the first character of the string, call the slice()
method on the string, passing 0
and 1
as start and end indexes:
const str = 'Protips'
const firstChar = str.slice(0, 1)
console.log(firstChar) // P
The slice()
method extracts a part of a string between the start and end indexes, specified as first and second parameters. It returns the extracted part as a new string and does not change the original string.
Get the first character of a string using at()
method
The at()
method takes an integer as input and returns the character of a string at the specified index. To get the first character of the string, call the at()
method on the string with a 0
index:
const str = 'Protips'
const firstChar = str.at(0)
console.log(firstChar) // P
The at()
method returns undefined
if the index does not exist:
console.log(str.at(9)) // undefined
The at()
method is a new addition to JavaScript and only works in modern browsers.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.