Get first character in string in JavaScript
In this tutorial, you are given a string. Get the first character in the string using JavaScript.
Solution
To get the first character in the given string using JavaScript, use String charAt() method. charAt()
method takes index as argument and returns the character at the index. If we pass 0 for index, then charAt()
returns the first character in the string.
str.charAt(0)
Program
1. Get the first character of the string value in str
variable, and print it to console output.
let str = 'hello world';
let firstChar = str.charAt(0);
console.log(firstChar);