1

I know how to run a script to generate and pad a number but I do not know how to unpad them. For example, 0008 means that there are 4 padding but the value of the padded number is 8.

function pad(num, size) {
    var s = num + "";
    while (s.length < size)
        s = "0" + s;
    return s;
} 

pad(8, 4);

However, how do I unpad them? Let's say I have a 0011 and I want to unpad the numbers to log only 11. Is there a solution for this?If I use the slice method then it will not work if the padded number is 0100 or 1000.

Krzyserious
  • 364
  • 4
  • 12
  • Use `parseInt()` way to get the unpad value. As simple as that – Ankit Agarwal May 10 '18 at 14:21
  • Possible duplicate of [Remove leading zeros from a number in Javascript](https://stackoverflow.com/questions/6676488/remove-leading-zeros-from-a-number-in-javascript) – tehhowch May 10 '18 at 15:04
  • Or of https://stackoverflow.com/questions/594325/truncate-leading-zeros-of-a-string-in-javascript – tehhowch May 10 '18 at 15:05

2 Answers2

1

Use parseInt() to the padded value to get unpad value. If you expect to have a string result for unpad values then you can use toSting() on the parsed value.

function pad(num, size) {
  var s = num + "";
  while (s.length < size) s = "0" + s;
  return s;
} 

var padded = pad(8, 4);
console.log('padded '+padded);
var unpad = parseInt(padded);
console.log('unpad '+unpad);


padded = pad(100, 4);
console.log('padded '+padded);
unpad = parseInt(padded);
console.log('unpad '+unpad);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

You can now use padStart() method for padding and + for unpadding. for example:

const x = "8";
const padded = x.padStart(4, 0);
console.log(padded) // "0008"
const unpadded = +x;
console.log(unpadded) // 8

Hope it could help anyone to get a code much cleaner.

MajidJafari
  • 1,076
  • 11
  • 15