1

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);

1
  • 4
    remove the char === as .test() will return a boolean for you Commented Aug 26, 2021 at 9:42

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

You also could achieve this by using regex:

const str = '1192.168.5.0';
const matches = [...str.matchAll(/\d/g)];

console.log(matches.length);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.