Open In App

JavaScript – How to Get the Last N Characters of a String?

Last Updated : 26 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the different methods to get the last N characters of a string in JavaScript.

1. Using slice() Method

The slice() method is the most commonly used approach for extracting the last N characters, thanks to its simplicity and support for negative indices.

JavaScript
const getChar = (s, n) => s.slice(-n);

const s = "Hello World";
console.log(getChar(s, 5)); 

Output
World

2. Using substring() Method

The substring() method calculates the starting index based on the string’s length.

JavaScript
const getChars = (s, n) => s.substring(s.length - n);

const s = "Hello World";
console.log(getChars(s, 5));

Output
World

3. Using Regular Expressions

You can use a regex pattern to extract the last N characters from a string. This approach is less common but effective in specific use cases.

JavaScript
const getChars = (s, n) => s.match(new RegExp(`.{${n}}$`))[0];

const s = "Hello World";
console.log(getChars(s, 5)); 

Output
World

4. Using Array.slice() After String Split

By splitting the string into an array, you can use Array.slice() to extract the last N elements and join them back.

JavaScript
const getChars = (s, n) => s.split("").slice(-n).join("");

const s = "Hello World";
console.log(getChars(s, 5));

Output
World

5. Using substr() Method

Although substr() is deprecated, it can still be used in some environments. It allows extracting the last N characters using a negative start index.

JavaScript
const getChars = (s, n) => s.substr(-n);

const s = "Hello World";
console.log(getChars(s, 5));

Output
World

6. Brute Force Approach

You can also manually iterate over the string to construct the last N characters. This method is less efficient and mainly for educational purposes.

JavaScript
const getChars = (s, n) => {
    let res = "";
    for (let i = s.length - n; i < s.length; i++) {
        res += s[i];
    }
    return res;
};

const s = "Hello World";
console.log(getChars(s, 5)); 

Output
World

Which Approach Should You Use?

ApproachWhen to Use
slice()Best for simplicity and modern JavaScript.
substring()Use when you prefer explicit index calculations.
RegexIdeal when working with patterns or dynamic N values.
Array.slice()Useful when working with array-like transformations.
substr()Use only if supporting legacy environments.
Brute ForceAvoid for real-world usage; use for educational purposes only.


Similar Reads