Back to Freecodecamp

Challenge 142: Sum the String

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69272dcf1c24b44fd79137c5.md

latest1.1 KB
Original Source

--description--

Given a string containing digits and other characters, return the sum of all numbers in the string.

  • Treat consecutive digits as a single number. For example, "13" counts as 13, not 1 + 3.
  • Ignore any non-digit characters.

--hints--

stringSum("3apples2bananas") should return 5.

js
assert.equal(stringSum("3apples2bananas"), 5);

stringSum("10cats5dogs2birds") should return 17.

js
assert.equal(stringSum("10cats5dogs2birds"), 17);

stringSum("125344") should return 125344.

js
assert.equal(stringSum("125344"), 125344);

stringSum("a1b20c300") should return 321.

js
assert.equal(stringSum("a1b20c300"), 321);

stringSum("a12b34c56d78e90f123g456h789i0j1k2l3m4n5") should return 1653.

js
assert.equal(stringSum("a12b34c56d78e90f123g456h789i0j1k2l3m4n5"), 1653);

--seed--

--seed-contents--

js
function stringSum(str) {

  return str;
}

--solutions--

js
function stringSum(str) {
  const matches = str.match(/\d+/g); // find all consecutive digits
  return matches.reduce((sum, num) => sum + Number(num), 0);
}