This is a clever little trick (that I think I've seen on SO before):
var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str
JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):
That is, with the above:
- 1 -> "0001"
- 12345 -> "12345"
Supporting negative numbers is left as an exercise ;-)
Happy coding.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…