1

i'm having a serious issue here. I have a function that pads a user's input with zeros. For example if i enter 88 it will normalize it to: 00000088. My function is this:

export default length => (value) => {
  const noLeadingZeros = value.toString().replace(/(0+)/, '');
  if (noLeadingZeros.length === 0) {
    return value;
  }
  return padLeft(noLeadingZeros, length);
};

with padleft is:

export default (num, len) => (
  len > num.toString().length ? '0'.repeat(len - num.toString().length) + num
    : num
);

My problem is that if i entered something like this: 80112345 it convert it to 08112345. Any ideas?

RamAlx
  • 6,976
  • 23
  • 58
  • 106

4 Answers4

2

In your replace, you're replacing all the zeros in the number not just those on the left side, and even if there are zeros on the left side, why remove them if you're just going to add them back. You could use a for loop that pads the string with a zero n times (where n is the number of digits that the string needs to have length 8), or (thanks to a comment by @AndrewBone), you can use the .repeat() function that does this for you:

function padLeft(value, len) {
  return '0'.repeat(String(value).length < len ? len - String(value).length : 0) + value;
}
console.log(padLeft("", 8));
console.log(padLeft("88", 8));
console.log(padLeft("00088", 8));
console.log(padLeft("12312388", 8));
console.log(padLeft("00000000", 8));
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 1
    I thought their `.repeat()` was quite nice already something like this would be nice https://jsfiddle.net/link2twenty/y3hco12x/ – Andrew Bone Mar 22 '18 at 14:45
2

Using slice:

let str = '00000000' + 88;
let resp = str.slice(-8, str.length)
console.log(resp) // 00000088
guijob
  • 4,413
  • 3
  • 20
  • 39
1

this looks wrong :

const noLeadingZeros = value.toString().replace(/(0+)/, '');

you are deleting every zeros out of your number... even those inside !

You can use this regex instead, instead of for /(0+)/ in your code :

 /\b(0+)/

explanation : the \b ensures the zeros are at the beginning of a word

or this

 /^(0+)/

explanation : the ^ ensure this is the beginning of the string

Pac0
  • 21,465
  • 8
  • 65
  • 74
1

Just use a RegEx to assert that the number is a valid number.

/0+/

Then get the number of digits in the number:

('' + num).length;

Then put the whole thing together

var paddedNum ='';
for (var i=0;i<8-len;i++) {
  paddedNum += "0";
}
paddedNum += num;
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80