代码之家  ›  专栏  ›  技术社区  ›  danday74

Javascript计算字符串中的数字[重复]

  •  -1
  • danday74  · 技术社区  · 3 年前

    “a4 bbb0 n22nn”

    这个字符串的期望答案是4。

    我的最佳尝试随之而来。在这里,我遍历每个字符来检查它是否是一个数字,但这似乎有点过于繁重。有没有更合适的解决办法?谢谢

    const str = 'a4 bbb0 n22nn'
    const digitCount = str.split('').reduce((acc, char) => {
      if (/[0-9]/.test(char)) acc++
      return acc
    }, 0)
    
    console.log('digitCount', digitCount)
    1 回复  |  直到 3 年前
        1
  •  3
  •   CertainPerformance    3 年前

    使用正则表达式执行全局匹配并检查结果匹配数:

    const str = 'a4 bbb0 n22nn'
    const digitCount = str.match(/\d/g)?.length || 0;
    console.log('digitCount', digitCount)