Instructions: The sumNums function takes a string as an argument. It should return the sum of all the numbers contained within the string. If there are no numbers in the string, sumNums should return 0.
Consecutive digits should be taken as a single number, e.g. "abc24def" would be 24, not 6.
Although there are multiple ways of achieving this, make sure to use a regular expression.
Example
sumNums('') // returns 0
sumNums('abcdef') // returns 0
sumNums('1') // returns 1
sumNums('123') // returns 123
sumNums('1hello2') // returns 3
sumNums('12hiya!3') // returns 15
function sumNums(str) {
let sum = 0;
for (let i =0; i<str.length;i++){
if (str[i].match(/^d+$/)) sum += Number(str[i]);
}
return sum;
}
FAILING ON THIS POINT:
should return the number when passed consecutive digits
AssertionError: expected 19 to equal 964
2
Answers
You can’t treat consecutive digits as a single number if you loop character by character.
Use a regular expression with the
g
modifier to find all the matches and return them as an array, and loop over this, rather than looping over individual characters.In addition to Barmer’s answer regarding the correctness of the OP’s regular expression this late provided answer promotes a more functional/method driven approach.
In order to never fail/throw, regardless of what has been passed to
sumNums
, one first would cast the provided value into a string-value which then gets processed bymatch
and a/the correct/ed regex where, with the help of the Nullish Coalescing Operator /??
, one always can expect an array as thematch
ing result.This array then (regardless whether empty or not) gets processed by
reduce
with an already classic callback which does sum-up theNumber
casted array items.The provided initial value of zero/
0
also serves the purpose of assuringsumNums
‘ default return value for provided values which do not contain any digit.