Sun Oct 24 2021·2 min read
Photo by Aziz Acharki
To get the last two characters of a string, call the
slice() method, passing
-2 as a parameter. The
slice method will return a new string containing
the last two characters of the original string.
const str = 'hello world'; const last2 = str.slice(-2); console.log(last2); // 👉️ ld
The parameter we passed to the String.slice method is the start index.
The start index is the index at which the method starts extracting characters from the string.
-2means - give me the last
2characters of the string.
This is the same as passing
string.length - 2 as the start index.
const str = 'hello world'; const last2 = str.slice(-2); console.log(last2); // 👉️ ld const last2Again = str.slice(str.length - 2); console.log(last2Again); // 👉️ ld
In both examples, we tell the
slice method to copy the last 2 characters of
the string into a new string.
Even if we try to get more characters than the string contains,
won't throw an error, instead it returns a new string containing all characters.
const str = 'h'; const last2 = str.slice(-2); console.log(last2); // 👉️ h
In this example, we tried to get the last
2 characters of a string that only
As a result the
slice method returned a copy of the entire string.
You could also use the String.substring method to get the last two characters of a string.
const str = 'one two'; const last2 = str.substring(str.length - 2); // 👉️ wo console.log(last2);
However, using the
String.slice method is more intuitive and readable.
String.substringmethod, it treats it as if you passed
0, which is very confusing.
For other differences between
String.slice, check out