1

I am converting the string month to an index in javascript. But the number needs to have a 2 digit month representation.

This line of code converts the index for me and adds one. This way I have the correct month.

How can I add 0 to the front of the index if the value of the index is only 1 digit? So basically if the month is any of the first 9 months how do I add a 0 in front of the number value of the month?

var expMonth = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"].indexOf(req.body.expMonth.toLowerCase()) + 1;

March would output 3. I need March to output 03 But I need October, November, December to output 10, 11, 12. Which they do as of my code now.

wuno
  • 9,547
  • 19
  • 96
  • 180
  • Dulpicate http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript – Rohan210 Dec 15 '16 at 08:08

1 Answers1

1

You can use String#slice method.

console.log(
  ('0' + 1).slice(-2), 
  ('0' + 10).slice(-2), 
  ('0' + 3).slice(-2)
)

With your code :

var expMonth = ('0' + (["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"].indexOf(req.body.expMonth.toLowerCase()) + 1)).slice(-2);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188