Valentin Tanasescu
Valentin Tanasescu

Reputation: 79

delete only the unnecessary 0s from the beginning of the number

I have a js string representing a number. I want remove only unnecessary 0s from the beginning of the string and put a 0 before comma if no digit exists, with regex:

var regex = ?
var replace = ?

new = "0001,3".replace(regex, replace); // 1,3
new = ",3".replace(regex, replace); // 0,3
new = "000,34".replace(regex, replace); // 0,34
new = "0201,3".replace(regex, replace); // 201,3
new = "0002,03".replace(regex, replace); // 2,03

I've tried:

new = string.replace(/^0+(,)/g, '$1').replace(/^,/g), '0,');

But looks like second replace doesn't work.

Upvotes: 0

Views: 131

Answers (2)

nick zoum
nick zoum

Reputation: 7285

Using Regex to replace the 0s.

function trim(txt) {
  return txt.replace(/^(0*)(,?)/, (full, zeros, end) => end ? "0," : "");
  // If the zeros are directly followed by a `,` then keep a `0`
  // use `function (){return arguments[2] ? "0," : "";}` for ES5
}

console.log(trim("0001,3"));
console.log(trim(",3"));
console.log(trim("000,34"));
console.log(trim("0201,3"));
console.log(trim("0002,03"));

Using parsing and stringify (will replace 0 at the start and the end)

function trim(txt) {
  return String(+(txt.replace(",", "."))).replace(".", ",");
}

console.log(trim("0001,3"));
console.log(trim(",3"));
console.log(trim("000,34"));
console.log(trim("0201,3"));
console.log(trim("0002,03"));

Upvotes: 3

Thomas
Thomas

Reputation: 12637

function trimZeroesLeft(txt) {
  return ("0" + txt).replace(/^0+(?=\d)/g, "");
}

function trimZeroesRight(txt) {
  return txt.replace(/,0*$|(,\d+?)0+$/g, "$1");
}

function trimZeroes(txt) {
  return ("0"+txt).replace(/^0+(?=\d)|,0*$|(,\d+?)0+$/g, "$1");
}


let arr = ["0001,3", ",300", "000,34", "0201,30", "0002,03", "012,0", "0,00"];

console.log("trimZeroesLeft", arr.map(v => `${v} -> ${trimZeroesLeft(v)}`));
console.log("trimZeroesRight", arr.map(v => `${v} -> ${trimZeroesRight(v)}`));
console.log("trimZeroes", arr.map(v => `${v} -> ${trimZeroes(v)}`));
.as-console-wrapper{top:0;max-height:100%!important}

Upvotes: 0

Related Questions