Last string character in JavaScript

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:

javascriptlet 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:

javascriptlet str = 'abcde';
let last = str.length - 1; // last character index

We use the found index to display the character on the screen:

javascriptlet str = 'abcde';
let last = str.length - 1; // last character index
alert(str[last]); // shows 'e'

The intermediate variable last can be omitted:

javascriptlet str = 'abcde';
alert(str[str.length - 1]); // shows 'e'
Задание 1

Given a string. Display its last character on the screen.

Задание 2

Given a string. Display its second-to-last character on the screen.

Задание 3

Given a string. Display its third-to-last character on the screen.