How to Get the Last N Characters of a String in JavaScript

Last updated on June 24, 2022
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
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also