How to get last ‘n’ characters of a string in JavaScript

Have you ever had a situation where you needed to get the last few characters of a string? Maybe it was an ID number, or some other identifier. As JavaScript developers, we have two simple ways to do this. The first one is using substring() and the second one is using slice(). Let’s take a look at both methods in greater detail. 

Table of Contents

substring()

The substring() method will return all characters from start index up until end index-1 (inclusive).

The following is a simple example of how to find the last few letters from a string:

const source = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
const charCount = 5;

console.log(source.substring(source.length - charCount));

//output: "iqua."

slice()

The slice() method is a handy and efficient way to get new arrays with portions of an existing array. It will not modify the original, but if you want those changes, just use it on one-way!

The method will return an object containing elements from index number (start) up until but not including index number (end). 

let source = 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.';
let charCount = 10;

console.log(source.slice(source.length - charCount));

As you see, it is qutie easy to retrive the latest characters from a string in JavaScript.

Leave a Comment

Your email address will not be published. Required fields are marked *