Calculate sum of all numbers present in a string | Function to calculate sum of all numbers present in a string containing alphanumeric characters ; A temporary string ; holds sum of all numbers present in the string ; read each character in input string ; if current character is a digit ; if current character is an alphabet ; increment sum by number found earlier ( if any ) ; reset temporary string to empty ; atoi ( temp . c_str ( ) ) takes care of trailing numbers ; input alphanumeric string ; Function call
function findSum ( str ) { let temp = " " ; let sum = 0 ; for ( let i = 0 ; i < str . length ; i ++ ) { let ch = str [ i ] ; if ( ! isNaN ( String ( ch ) * 1 ) ) temp += ch ; else { sum += parseInt ( temp ) ; temp = " " ; } } return sum + parseInt ( temp ) ; } let str = " " ; document . write ( findSum ( str ) ) ;