Code snippet for counting the number of digits in string, how to write it to work?
const str = "192.168.5.0"
const digits = [...str].reduce((a, char) => char === /\d/.test(char) ? ++a : a, 0);
console.log(digits);
You can utilize that the unary plus operator converts true to 1 and false to 0. Just convert the boolean returned by test() to number this way, and add the result to the counter in reduce(). 1 will be added when the charatcter is a digit and 0 if it's not.
const str = "192.168.5.0"
const digits = [...str].reduce((n, char) => n + +/\d/.test(char), 0);
console.log(digits);
You can also use a simple for...of loop:
const str = '1192.168.5.0';
let count = 0;
for (let ch of str) ch >= "0" && ch <= "9" && count++;
console.log(count);
char ===as.test()will return a boolean for you