Let's say we have some string. Each character
in this string has its own order index: the
first character index is 0
, the second
is 1
, the third is 2
and so on.
As you've already noticed, character numbering starts from zero (zero as the start of numbering is often found in programming).
If it is necessary, you can access a specific character of a string by its index. To do this, the name of the variable is written, after this name square brackets are placed, and in these brackets the character index is inserted.
Let's look at an example. Let's say we have a string like this:
let str = 'abcde';
Let's refer to some of the characters in this string:
let str = 'abcde';
alert(str[0]); // shows 'a'
alert(str[1]); // shows 'b'
alert(str[2]); // shows 'c'
The character index can also be stored in a variable:
let str = 'abcde';
let num = 3; // the character index in variable
alert(str[num]); // shows 'd'
Given the string 'abcde'
.
Referring to the individual characters of
this string, print the character 'a'
,
the character 'c'
,
the character 'e'
.
Given a variable with the string
'abcde'
. Referring to the individual
characters of this string, write the
characters of this string in reverse order
into a new variable, that is, 'edcba'
.
Given the variable str
with the
string 'abcde'
and the variable
num
with the character index.
Display on the screen the character whose number is
stored in the variable num
.