简体   繁体   中英

How to calculate digit containing in string in javascript?

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;

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM