Kage Kage - 2 months ago 7
Javascript Question

How would I go about adding together numbers within the same string in javascript?

If I have the string "5246-9346-7341-8534" already set as a variable (cardOne) is there a more efficient way to add all of the numbers in that string together than typing out console.log(5 + 2 + 4 + 6 + 9 + etc. . .)

Answer

You just need to remove the dashes, do a loop over all the characters, parse them as integers, and add them up.

var s = "5246-9346-7341-8534";
var sum = 0;
var i;
s = s.replace(/-/g, "");
for (i = 0; i < s.length; i++) {
    sum += parseInt(s.substr(i, 1));
}
console.log(s, "=", sum); // 74

(I didn't just do your homework for you, did I?)

Comments