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.
-
will the structure be always same?Anoop Joshi P– Anoop Joshi P2014年08月18日 12:02:50 +00:00Commented Aug 18, 2014 at 12:02
-
look at stackoverflow.com/questions/3955345/…user3913686– user39136862014年08月18日 12:03:22 +00:00Commented Aug 18, 2014 at 12:03
-
@AnoopJoshi - no the string would be different almost every timeSaiyanToaster– SaiyanToaster2014年08月18日 12:04:40 +00:00Commented Aug 18, 2014 at 12:04
-
what is source of strings, are they being concatenated with numbers at server?charlietfl– charlietfl2014年08月18日 12:05:18 +00:00Commented Aug 18, 2014 at 12:05
-
@terribleProgrammer - this is an example of always having the same thing before the number? I'm talking about random strings from a set.SaiyanToaster– SaiyanToaster2014年08月18日 12:05:42 +00:00Commented Aug 18, 2014 at 12:05
3 Answers 3
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.
1 Comment
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.
1 Comment
+0.3 health per level (+5.4 at champion level 18) ignore (+5.4 at champion level 18)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 :|