How to Get the Last N Characters of a String in JavaScript
To get the last N
characters of a string in JavaScript, call the slice()
method on the string, passing -N
as an argument. For example, str.slice(-3)
returns a new string containing the last 3 characters of str
.
const str = 'Coding Beauty';
const last3 = str.slice(-3);
console.log(last3); // uty
const last6 = str.slice(-6);
console.log(last6); // Beauty
const last10 = str.slice(-10);
console.log(last10); // ing Beauty
The String()
slice()
method returns the portion of a string between the start and end indexes, which are specified by the first and second arguments respectively. When we only specify a start index, it returns the entire portion of the string after this start index.
When we pass a negative number as an argument, slice()
counts backward from the last string character to find the equivalent index. So passing -N
to slice()
specifies a start index of str.length - N
.
const str = 'Coding Beauty';
const last6 = str.slice(-6);
console.log(last6); // Beauty
const last6Again = str.slice(str.length - 6);
console.log(last6Again); // Beauty
See also
- How to Get the Last Two Characters of a String in JavaScript
- How to Get the First N Characters of a String in JavaScript
- How to Split a String Every N Characters in JavaScript
- How to Get the Last Character of a String in JavaScript
- How to Get the First Two Characters of a String in JavaScript
- How to Get the Last Part of a URL in JavaScript