To get the first character of a string in JavaScript, you can use array-like indexing or the charAt()
method.
In this example,
str
with a value of "Hello World"
.charAt()
method with index 0 on the string str
.let str = "Hello World";
let firstChar = str[0];
console.log(`First character: ${firstChar}`);
First character: H
In this example,
str
with a value of "apple"
.charAt()
method with index 0 on the string str
.let str = "apple";
let firstChar = str.charAt(0);
console.log(`First character: ${firstChar}`);
First character: a
In this tutorial, we learned How to get First Character in String in JavaScript language with well detailed examples.