How To Get Last 4 Digits Of A Number In Javascript

Getting the last 4 digits of a number is a common task when working with financial or personal identification numbers. In JavaScript, there are several ways to achieve this, but in this tutorial, we will show you the easiest and most straightforward method.

Step 1: Convert the Number to a String

To extract the last 4 digits of a number, we must first convert it to a string using the toString() method. This method returns a string representation of the number, allowing us to access individual characters and substrings.

In this example, we have assigned the number 1234567890 to the variable ‘number’ and converted it to a string using the toString() method.

Step 2: Use the .slice() Method to Extract the Substring

Once we have the number as a string, we can use the .slice() method to extract the last 4 digits. This method extracts a section of the string and returns it as a new string.

Here, we have used the .slice() method with a negative number (-4) as the argument. This tells the method to start slicing from the end of the string and to extract the last 4 characters.

Step 3: Display the Last Four Digits

Finally, we can display the last four digits of the original number by outputting the ‘lastFour’ variable.

This will display an alert box containing the last four digits of the original number.

And that’s it! With just a few lines of code, we have extracted the last four digits of a number in JavaScript.

If you need to extract a different number of digits, you can simply adjust the argument for the .slice() method. For example, to get the last 6 digits, you would change the code to:

Remember to always convert the number to a string first before using the .slice() method.

You can find more information about the .slice() and toString() methods on the MDN Web Docs website.

Full code: