0

I have a function and I want to calculate digit that contains in a string.

str='hel4l4o';

The code that I created:

function sumDigitsg(str) {
var total=0;
if(isNaN(str)) {
  total +=str; 
  console.log(total);
}
  //console.log(isNaN(str));
  return total;

}
2
  • what is your expected output and what do you mean by "calculate digit"? Commented Jun 2, 2019 at 7:09
  • expected output 8 after adding 4 + 4 from string.. Commented Jun 2, 2019 at 7:11

1 Answer 1

1

You can do this using regex to match all digits (.match(/\d+/g)) and then use .reduce to sum the digits matched:

const str = 'hel4l4o';
const total = str.match(/\d+/g).reduce((sum, n) => sum + +n, 0);
console.log(total);

As for your code, you need to loop through your characters and then check if it is a number using if(!isNaN(char)). After that you need to turn the character into a number by using something like the unary plus operator (+char) such that you can add it to total:

let str = 'hel4l4o';

function sumDigitsg(str) {
  let total = 0;
  for(let i = 0; i < str.length; i++) {
    let char = str[i];
    if (!isNaN(char)) {
      total += +char;
    }
  }
  return total;
}

console.log(sumDigitsg(str));

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

1 Comment

can u please help me to answer this question. stackoverflow.com/questions/56409738/…

Your Answer

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