Borislav Hadzhiev
Tue Oct 05 2021·2 min read
Photo by John Gibbons
To get the last N characters of a string, call the slice
method on the
string, passing in -n
as a parameter, e.g. str.slice(-3)
returns a new
string containing the last 3 characters of the original string.
const str = 'Hello World'; const last3 = str.slice(-3); // 👉️ rld console.log(last3); const last2 = str.slice(-2); // 👉️ ld console.log(last2);
The parameter we passed to the String.slice method is the start index.
-3
means give me the last 3
characters of the string.This is the same as passing string.length - 3
as the start index.
const str = 'Hello World'; const last3 = str.slice(-3); // 👉️ rld console.log(last3); const last3Again = str.slice(str.length - 3); // 👉️ rld console.log(last3Again);
In both examples, we tell the slice
method to copy the last 3 characters of
the string into a new string.
Even if we try to get more characters than the string contains, String.slice
won't throw an error, instead it returns a new string containing all characters.
const str = 'Hello World'; const last100 = str.slice(-100); // 👉️ Hello World console.log(last100);
In the example we tried to get the last 100
characters of a string that only
contains 11
characters.
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 N characters of a string.
const str = 'Hello World'; // 👇️ using substring const last3 = str.substring(str.length - 3); // 👉️ rld console.log(last3);
However, using the String.slice
method is more intuitive and readable.
String.substring
method, it treats it as if you passed 0
, which is very confusing.For other differences between String.substring
and String.slice
, check out
the
MDN docs.