JavaScript Code

How to get first character in string?


Problem Statement

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

get the first character of the string value in str variable

let str = 'hello world';
let firstChar = str.charAt(0);
console.log(firstChar);