Question

I have a simple app that allows me to caculate the total amount invoiced and deposited in a route. However I want to allow the user to input multiple values in a single input field; e.g: 500+50+36.5-45.2-10.

I have written a function that will retrieve this input and then split this string into elements of an array at the + sign and immediately parse the values to numbers and then add them and return the total the user inputs into each individual field. This is all well as long as the user does no use any sign other than +.

I have searched the use of regexp:

but none of the results seem to work. How could I make my code retrieve the values so that the negative values get passed into the array as negative values?

Here is a snippet of my Js code: For the full code, visit my fiddle.

totalInvoiced: function () {

    var a = A.invoiced.value;
    var value1Arr = []; 
        value1Arr = a.split("+").map(parseFloat);
    var value1 = 0;
        value1Arr.forEach(function (value) {
        value1 += value;
    });
Was it helpful?

Solution

I really like PhistucK's solution, but here an alternative with regex:

value1Arr = a.split(/(?=\+|\-)/);

This will split it, but keeps the delimiter, so the result will be:

["500", "+50", "+36.5", "-45.2", "-10"]

OTHER TIPS

A bit dirty, but maybe a.replace(/-/g, "+-").split("+"), this way, you add a plus before every minus, since the negative numbers just basically lack an operator.

You can use this pattern that splits on + sign or before - sign:

var str = '500+50+36.5-45.2-10';

console.log(str.split(/\+|(?=-)/));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top