Skip to content Skip to sidebar Skip to footer

Sum Two Capture Groups

I need get two values from a string and sum them. var text = 'SOC 01 672 1.653.806,08 18.512,98 1.667.621,57 2.647,38 07 23 12.965,11 0,00 12.965,11 0,00 13 5 10.517,81 0,00 10.517

Solution 1:

You're going to have to do something like:

Number(match[1].replace(/[\.,]/g, ''))

To strip out the .s and ,s before summing the numbers.

If you need to get the number back into the same format, you can do something like this:

var total = Number(match[1].replace(/[\.,]/g, '')) + Number(match2[1].replace(/[\.,]/g, ''));

var result = String(total);
result = result.replace(/(?=\d{2}$)/, ',');
result = result.replace(/\B(?=(\d{3})+(?!\d))/g, '.');

Which produces 1.680.586,68. I have the same question as stribizhev about how you are doing the summing.

Here is the fiddle for the above example: https://jsfiddle.net/qw700fq9/

Here is the updated fiddle - cleaned it up a bit: https://jsfiddle.net/rdu15ds3/

Also, adding the decimals back in was based on the answers to this question: How to print a number with commas as thousands separators in JavaScript

Solution 2:

The regex is returning a string. You need to convert them to numbers before adding them.

functiontoNumber(n){
    returnparseFloat(n.replace(/./g,'').replace.(/,/g,'.'));
}

toNumber(+match[1]) + toNumber(+match2[1]);

Post a Comment for "Sum Two Capture Groups"