You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript正则校验禁止前导零的纯数字字符串?

解决带前导零的纯数字字符串校验问题

原代码使用正则/^\d+$/校验纯数字字符串,但会误将01、0080这类带前导零的字符串判定为有效数字。需要调整校验逻辑,禁止带前导零的数字(单独的0除外)。

修改方案

把校验正则替换为/^(0|[1-9]\d*)$/,该正则的规则是:

  • ^ 匹配字符串开头
  • 0 匹配单独的数字0
  • | 逻辑或
  • [1-9]\d* 匹配以1-9开头,后面跟任意数量数字的字符串(避免前导零)
  • $ 匹配字符串结尾

修改后的完整代码

const arr = ["01/05/2023", "1ert", "0fer", "blah", "0", "", "123", "1e3", "1*4", "0080", "1.34", "1,00", "-2"]

function validNumber (a) {
  let regex = /^(0|[1-9]\d*)$/;
  a.forEach((string) => {
    if(!string.match(regex)) {
        console.log("not a number:", string)
    } else {
      console.log(parseInt(string))
    }
  })
}

执行结果说明

运行修改后的代码,只有以下两个字符串会被判定为有效数字:

  • 0 → 输出 0
  • 123 → 输出 123

其余字符串(包括0080、01/05/2023等)都会被输出为not a number。

内容的提问来源于stack exchange,提问作者JayyRon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:48:27