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.

2
  • 2
    Probably duplicate of: stackoverflow.com/questions/2998784/… Commented Mar 26, 2019 at 16:58
  • A simple web search should have answered this for you. Basic research is expected here before asking questions Commented Mar 26, 2019 at 17:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

The number of leading 0's is unknown. The input could be 01 or 001 or 0001 or 00001. When added, I would like the result to be 02, 002, 0002 and 00002 respectively.
.split('') is unneccessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.