After getting this answer from aduch:
With this regex:
/((-|\+)?([0-9]+|)(\.?[0-9]+))/g
You can use Array.prototype.reduce like this to sum your 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 be equal to -8.5 here
Note that `str.match(re)` may return `null`, so we just make sure we call `reduce` on an array.
I was wondering if it were possible to ignore things in brackets, as well as what is currently there.
Here is an example of the strings that will be added together:
+0.08 attack damage per level (+1.35 at champion level 18)
It current adds everything in the string, which yes - I did ask for, but it doesn't add 0.08
to itself and 1.35
to itself, it merges them together.
I'd either like them to be separate, as one is in brackets and one isn't or just to ignore the content within the brackets. (content after "level .." within the brackets should be ignored in all cases)