Let's output the last character of the string. At the same time, we will make sure that our script determines the number of the last character itself, regardless of the string length.
Let us have such a string:
let str = 'abcde';
As you can see, the number of characters
in this string is 5
. If we think a little,
it becomes obvious that since the numbering of
characters starts from zero, hence the index
of the last character of this string will be
1
less than its length.
It turns out that knowing the length of
the string, we can subtract 1
from
it and retreive the index of the last
character, and then you can get the last
character itself by this index.
As you already know, the length of a string
can be found using the length
property.
Based on this, we find the index of the last character:
let str = 'abcde';
let last = str.length - 1; // last character index
We use the found index to display the character on the screen:
let str = 'abcde';
let last = str.length - 1; // last character index
alert(str[last]); // shows 'e'
The intermediate variable
last
can be omitted:
let str = 'abcde';
alert(str[str.length - 1]); // shows 'e'
Given a string. Display its last character on the screen.
Given a string. Display its second-to-last character on the screen.
Given a string. Display its third-to-last character on the screen.