gpt4 book ai didi

javascript - 仅删除数字开头不必要的 0

转载 作者:行者123 更新时间:2023-12-01 00:51:22 24 4
gpt4 key购买 nike

我有一个代表数字的js字符串。我只想从字符串开头删除不必要的 0,如果不存在数字,则在逗号前添加 0,使用正则表达式:

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

我已经尝试过:

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

但看起来第二次替换不起作用。

最佳答案

使用正则表达式替换 0

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"));

使用解析和字符串化(将替换开头和结尾的 0)

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"));

关于javascript - 仅删除数字开头不必要的 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56947950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com