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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -