0

(This is not a duplicate. I can't find the solution in the link provided).

Say I have an input from a user in an html form intended as a serial number or some such. This number can start with 0s. Example, 0001.

In Javascript, if that number (0001) is incremented, it becomes 2.

I would like to preserve the leading 0s to get 0002.

How do I do that in Javasript?

Thanks in anticipation.

Nick
  • 37
  • 5
  • 2
    Probably duplicate of: https://stackoverflow.com/questions/2998784/how-to-output-integers-with-leading-zeros-in-javascript – MonneratRJ Mar 26 '19 at 16:58
  • A simple web search should have answered this for you. Basic research is expected here before asking questions – charlietfl Mar 26 '19 at 17:01

1 Answers1

1

Use padStart to pad the start of a number. However numbers don't start with zero so the number will have to be displayed as a string.

To find the number of zeros, you can do:

('001'.match(/^0+/) || [''])[0].length
  • '001'.match(/^0+/) – matches as many zeros as possible from the start of the string
  • || [''] – if the match returns undefined, use an array with an empty string (aka a fallback value)
  • [0] – get the first value in the returned array (either the match or the fallback)
  • .length – get the length of the string

let nums = [
  '1',
  '01',
  '001',
  '0001'
]

let str = ''

for (let i of nums) {
  let numZeros = (i.match(/^0+/) || [''])[0].length
  let num = Number(i)
  while (num < 20) {
    str += `<p>${String(num++).padStart(numZeros + 1, '0')}</p>`
  }
}

document.body.innerHTML = str
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338