Access Character in String using []
In JavaScript, you can access individual characters in a string using square bracket notation, as shown in the following.
Syntax
str[n]
where
str
is a string[]
is square bracket notationn
is index
str[n]
returns the character from the string str
present at the index n
.
Examples
1. In the following program, we get the character in string name
at index=3.
let name = 'apple';
let output = name[3];
console.log(output);
2. In the following program, we take a value from index n
, such that this index is out of the range for given string length. str[n]
returns undefined
.
let name = 'apple';
let output = name[15];
console.log(output);