Nick
Nick

Reputation: 47

How to add numbers with 0s in front in Javascript?

(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.

Upvotes: 0

Views: 127

Answers (1)

Get Off My Lawn
Get Off My Lawn

Reputation: 36351

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

Upvotes: 1

Related Questions