Search code examples
javascriptecmascript-6template-literals

JS ES6 template literals and leading/suffix zeros to number


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"?)


Solution

  • 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"