Home > Back-end >  js regex replace zero
js regex replace zero

Time:08-21

I need to remove 0 in the string to get a normal number, e.g.:

001    ~ 1
0002   ~ 2
020    ~ 20
0.500  ~ 0.5

CodePudding user response:

Converting such a string to a Number will remove redundant trailing and leading zeroes. You can then convert it back to a String:

const formatted = String(Number(input));

CodePudding user response:

Here is a regex that uses a positive lookahead to exclude numbers like 0.5:

[ '001', '0002', '020', '0.500' ].forEach(str => {
  let trimmed = str.replace(/^0 (?=[1-9])/, '');
  console.log(str   ' => '   trimmed);
});

Output:

001 => 1
0002 => 2
020 => 20
0.500 => 0.500
  • Related