In Python it's possible to append leading zeros to number when building a string like this
print "%02d" % (1)
//>> "01"
Is it possible to do the same with ES6 template literals?
(If, is it also possible to do the same with spaces instead of zeros: " 1"?)
JavaScript doesn't keep insignificant leading zeros around.To add leading zeros to a number: Use the String() object to convert the number to a string. Call the padStart() method to add zeros to the start of the string. The padStart method will return a new, padded with leading zeros string.
Template Literals is an ES6 feature (JavaScript 2015).
Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.
String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well.
You can use the string function padStart
by converting the number to string with toString()
and then padding with padStart
where the first argument is the length and the second is what to pad with.
let n = 1;
n.toString().padStart(2, "0")
//=>"01"
If your numbers can only be between 0 and 99 then try this:
for (let n = 0; n < 10; n++) {
console.log(n.toString().padStart(2, "0"));
}
If you want to use spaces then try this:
for (let n = 0; n < 10; n++) {
console.log(n.toString().padStart(2, " "));
}
If you don't want to use padStart
then try this:
for (let n = 0; n < 100; n+=5) {
console.log(('0'+n.toString()).slice(-2));
}
Or even this:
for (let n = 0; n < 100; n+=5) {
console.log(`0${n}`.slice(-2));
}
This last one uses the ES6 literals but still uses the slice
to only get the last 2 characters.
To use spaces on the last two just change the 0
to ` space.
String.padStart
is only available on newer browser versions. So you might need a polyfill.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
You could try prepending the maximum width as a fixed string of characters to the value then slice the resulting string to size.
Example: Let's say you want your numbers left padded with a period to a maximum width of 6
console.log((`......${123}`).slice(-6)); // ...123
console.log((`......${12345}`).slice(-6)) // .12345
const v = 99;
console.log((`......${v}`).slice(-6)) // ....99
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With