jquery - Finding numbers in a string and adding them together -
i wondering if possible jquery add numbers in string...
the strings can added shown in examples below. if 1 or more of string appears, should combined.
all possible strings: click here
example possible strings:
+0.53 attack damage +0.53 attack damage = 1.06 attack damage +8.75 mana +8.75 mana = 17.5 mana
each of these can combined 9 times.
with regex:
/((-|\+)?([0-9]+|)(\.?[0-9]+))/g
you can use array.prototype.reduce sum numbers up
var str = 'hello +0.50 world hello 1 world hello -10 world', re = /((-|\+)?([0-9]+|)(\.?[0-9]+))/g, sum; sum = (str.match(re) || []).reduce(function (prev, current) { if (object.prototype.tostring.call(prev) !== '[object number]') { prev = parsefloat(prev, 10); } return prev + parsefloat(current, 10); }, 0); // sum should equal -8.5 here
note str.match(re)
may return null
, make sure call reduce
on array.
Comments
Post a Comment