使用正则表达式从字符串中删除第一个零值

Yas*_*adi 2 regex

我使用 padStart 方法(padLeft)创建了一个字符串值,例如:

"5".padStart(19, "0")
Run Code Online (Sandbox Code Playgroud)

这导致“0000000000000000005”如何使用正则表达式取回那 5 个?我已经测试过这个:

/^0*(\d+)$/.exec(d)[1]
Run Code Online (Sandbox Code Playgroud)

正确返回 5 。

但是这个正则表达式为“00000012.22”之类的东西返回null

样品:

5 > 5

005 > 5

0011.22 > 11.22 >> 这是第一个问题!

00100 >> 100

001001 >> 1001

00.5 >> 0.5这是第二个问题!

工作代码但没有正则表达式:

function toDb(d) {
        if (d == null) return null;
        var precisionIndex = d.indexOf('.');
        return d.toString().padStart((29 + precisionIndex + 1), '0');
        }

function fromDb(d) {
            if (d == null) return null;
            d = d.replace(/^0+/, ''); // I'd like to use regex here
            if (d.indexOf('.') == 0) // I'd like to use regex here
                d = '0' + d; // I'd like to use regex here
            return d;
    }
Run Code Online (Sandbox Code Playgroud)

fromDb(toDb('0.5')) 为我返回 0.5。但我想在我的代码中使用正则表达式。

Pra*_*lan 5

使用String#replace方法替换领先0

console.log(
  "0000000000000000005".replace(/^0+(?=\d)/, '')
)

console.log(
  "000000000000000000.5".replace(/^0+(?=\d)/, '')
)
Run Code Online (Sandbox Code Playgroud)

在正则表达式start anchor( ^) 中, 断言字符串的开始位置并0+匹配 的一个或多个重复的组合0,一起^0+匹配0开头的 s。

更新:为了避免0.使用正前瞻断言之前删除,(?=\d)匹配0数字后面的 。