Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
Assertion error on number of digits in a string

My code works for some input but for an input like this: ('This'+ 'painting'+ '1845 and 1910') I get an error: AssertionError 7 == 8. I can solve it using regular expression but I don't know what I'm doing wrong in this. Thanks for answering.

import assert from "assert";

function countDigits(text){
    
    let num = text.split('');
    let sum = 0;
    for (let i=0; i<num.length; i++){
        if (Number(num[i])) {
            sum += 1;}}
    return sum
}

assert.equal(countDigits('This'
 + 'painting'
 + '1845 and 1910'), 8);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Number(num[i]) will include "0" conversion to a number but in Javascript's if condition, it will be falsy

if(Number("0")) {
  console.log('true') //you're expecting this because it's a number
} else {
  console.log('false') //but in fact, it returns this because 0 is falsy
}

In that case, I'd suggest you use isNaN(num[i])

function countDigits(text) {

  let num = text.split('');
  let sum = 0;
  for (let i = 0; i < num.length; i++) {
    //num[i] = " " will be considered a number, so we need to check it as well
    if (num[i] !== " " && !isNaN(num[i])) {
      sum += 1;
    }
  }
  return sum
}

console.log(countDigits('This' +
  'painting' +
  '1845 and 1910'))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!