0

I need to convert 012345 to '012345'. toString() and String() removes 0. How can I reserve it?

The reason I am asking is because of this question: Write a JavaScript program that accepts a number as input and insert dashes (-) between each two even numbers. For example if you accept 025468 the output should be 0-254-6-8.

user2734550
  • 952
  • 1
  • 12
  • 35
  • Put it back after converting? – Pointy Jun 30 '15 at 01:34
  • 1
    This seems very similar to this older question. http://stackoverflow.com/questions/8559021/javascript-number-preserve-leading-0 – userFriendly Jun 30 '15 at 01:36
  • 2
    Your question is unclear. `'012345'` is already a string and `'012345'.toString()` yields the same string, `'012345'`. See for yourself: https://jsfiddle.net/x3a7pn7x/ – Jordan Running Jun 30 '15 at 01:42
  • Hi jordan, you misunderstood. that period is the sentence period. There is a space between . and toString() – user2734550 Jun 30 '15 at 01:44
  • @Abi, those are java solutions. my tag is javascript – user2734550 Jun 30 '15 at 01:46
  • You're trying to solve the wrong problem. If the user enters `025468` into an `` then it's already a string. You'll only lose that leading `0` if you try to convert it to a number. Don't convert the whole string into a number—treat the string as a series of characters, and as you read each character you can convert it to a number to test whether or not it's even. – Jordan Running Jun 30 '15 at 01:59
  • oh! I missed the word "as input". Thanks for pointing that out. If you rewrite that as answer, i will accept it – user2734550 Jun 30 '15 at 02:03
  • @RobG but the linked question won't answer the second part of the question. – Avinash Raj Jun 30 '15 at 02:04
  • for the second part `console.log("025468".replace(/([02468])(?=[02468])/g, "$1-"))` – Avinash Raj Jun 30 '15 at 02:09

0 Answers0