0

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

"a4 bbb0 n22nn"

Desired answer for this string is 4.

My best attempt follows. Here, I'm iterating through each char to check if its a digit but this seems kinda heavy handed. Is there a more suitable solution? thx

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)
danday74
  • 45,909
  • 39
  • 198
  • 245

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
  • 313,535
  • 40
  • 245
  • 254