Skip to content

Pad a number with leading zeros in JavaScript

In JavaScript, to pad a number with leading zeros, we can use the padStart() method. The padStart() method pads the current string with another string until the resulting string reaches the given length. The padding is applied from the start of the current string.

Advertisements

Syntax

str.padStart(targetLength, <padString>)

targetLength is the length of the string to be returned, padString is the source string, by default is empty string (” “).

Examples

const toBePadded = '99';
console.log(toBePadded.padStart(5, '0')); //00099
Advertisements

You can mask a few characters in a string like:

const creditCardNumber = '2034399002125581';
const ccNumberWithoutFirstNumber = creditCardNumber.slice(4,creditCardNumber.length);
const maskedNumber = ccNumberWithoutFirstNumber.padStart(creditCardNumber.length, '*');
console.log(maskedNumber); //****399002125581

See also  How to convert a string into integer in JavaScript?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.