-1

I was wondering if it were possible with jQuery to add together numbers in a string...

The strings can only be added to themselves as shown in the examples below. If one or more of the string appears, it should be combined.

All the possible strings: click here

Example with 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 be combined up to 9 times.

SaiyanToaster
  • 138
  • 1
  • 1
  • 10

3 Answers3

1

Iterate through the characters of the string (by making substrings with length 1); once you detect a number or a decimal point, save the start position in a variable. Then, once you detect something that is not a number or decimal point, or a second decimal point (count the number of decimal points), the number has ended; save the end position and voilà, you have the start and end position of the number and can get it by making a substring.

return true
  • 7,839
  • 2
  • 19
  • 35
0
var strs = [
  "Hello 1 World",
  "Hello 2 World"
];

var n = 0;
strs.forEach(function(str) {
  str.match(/[\d|\.|\-]+/g).forEach(function(num) {
    n+= window.parseFloat(num);
  });
});

Edit: Oh, that "list of possible strings" (with percentage values etc) changed the game. Well, start with this and improve the implementation :|

Samuli Hakoniemi
  • 18,740
  • 1
  • 61
  • 74
0

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.

axelduch
  • 10,769
  • 2
  • 31
  • 50
  • Would it be possible to ignore things within brackets? Example: `+0.3 health per level (+5.4 at champion level 18)` ignore `(+5.4 at champion level 18)` – SaiyanToaster Aug 18 '14 at 12:43