0

Yep, the title says pretty much everything. Basically I want a default X-digit number which is all zeros. Then, from this number, I want to replace the last characters with other numbers. For example, if I have '434', and the default is '000000', the result should be '000434'.

In Ruby, this is the equivalent of doing '%.6d' % 434 and it returns '000434'. If the number I want to save has more than 6 digits, I just use that number instead. I realized that as I'm working with strings I could use this solution:

let base = '000000'
let str = '434'
console.log(base.slice(0, -str.length) + str)

Buuut, even if it's a simple approach, I don't know if it's the best. What daya' think?

2 Answers2

2

For compatibility with older JS environments, you can depend only on a simpler slice:

(base + str).slice(-6)

For modern ones, padStart is available:

str.padStart(6, '0')   // or String(num)
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

JavaScript has string.padStart(length, padString)

let str = '434'
const updated = str.padStart(6, '0')
console.log(updated)
epascarello
  • 204,599
  • 20
  • 195
  • 236