Introduction
In this lab, we will be exploring the concept of padding a given number to a specified length using JavaScript. We will be using the String.prototype.padStart() method to pad the number and convert it to a string. Through this lab, you will gain a better understanding of how to manipulate strings and numbers in JavaScript.
How to Pad a Number in JavaScript
To pad a number in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
String.prototype.padStart()method to pad the number to the specified length, after converting it to a string. - The
padNumber()function below demonstrates this approach. - Pass the number and the desired length as arguments to the function.
- The function returns the padded number as a string.
const padNumber = (n, l) => `${n}`.padStart(l, "0");
Example usage:
padNumber(1234, 6); // '001234'
Summary
Congratulations! You have completed the Pad Number lab. You can practice more labs in LabEx to improve your skills.