0

I want to know how many digits 0 to 9 are in a string:

"a4 bbb0 n22nn"

The desired answer for this string is 4.

My best attempt follows. Here, I'm iterating through each char to check if it's a digit, but this seems kind of heavy-handed. Is there a more suitable solution?

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)
halfer
  • 19,824
  • 17
  • 99
  • 186
danday74
  • 52,471
  • 49
  • 232
  • 283

1 Answers1

4

With the regular expression, perform a global match and check the number of resulting matches:

const str = 'a4 bbb0 n22nn'
const digitCount = str.match(/\d/g)?.length || 0;
console.log('digitCount', digitCount)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320