Forum Moderators: open

Message Too Old, No Replies

Trying to replace with a regexp

         

RevoltPuppy

9:53 pm on Jun 26, 2008 (gmt 0)

10+ Year Member



I'm trying to write an automatic calculator, that takes numbers entered into a form and adds them together. I also want to strip out bad characters like the dollar sign, commas, and trailing decimal places (e.g. change $3,000.00 to 3000). The script will add up each number if they're entered properly (see the default values when the array is created), but when I hit the "replace" line, everything craps out.

Comment that line out, and everything works just fine, but it doesn't remove any bad characters that a user is likely to enter.

<script type="text/javascript">
function calculate(){
var costs = new Array();
costs[0] = 8;
costs[1] = 3;
costs[2] = 18;
costs[3] = 18;

//Convert costs to proper numbers
for (i=0; i<=3; i++){
costs[i] = costs[i].replace(/(\.00¦\$¦\,)/g, "");//Here is where the code craps out. I want to get rid of undesirable characters: .00, $, and , (comma)
costs[i] = parseInt(costs[i]); //Convert each array item to a number
//alert(i + " " + costs[i]);

//Convert NaNs to 0
if (isNaN(costs[i])){
costs[i] = 0;
}

}
var totalCosts = document.getElementById("total-costs");//Get total-costs div to change page content

totalCosts.innerHTML = costs[0] + costs[1] + costs[2] + costs[3];
}

calculate();
</script>

poppyrich

5:27 am on Jun 27, 2008 (gmt 0)

10+ Year Member



The syntax of the regular expression is the problem, as you seem to know since everything else works, OK.

these two regexes, in sequence, should do it.
// replace out the .00 at end
costs[i]=costs[i].replace(/\.00$/g,'');
// strip out all non-numeric characters in what's left
costs[i]=costs[i].replace(/[^0-9]+/g,'');

I'm sure there's a way to combine it into one regex but I'd have to go checking. Always forget the syntax and have to brush up.

httpwebwitch

2:11 pm on Jun 27, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Are your numbers always going to be integers? You're adding your dollars, but not making cents. (sorry for the pun)

It can all be done in one line:
just strip out anything that isn't [0-9] or "."

".00" is not undesirable, it's just zero with two extra significant digits. you can keep the ".00" in your number, since "1.00" is the same as "1" when you're adding numbers together.

costs[i]=costs[i].replace(/[^0-9\.]+/g,'');

After the noisy characters are removed, use parseFloat instead of parseInt

g1smd

2:19 pm on Jun 27, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Depending on culture there are a variety of input formats that people may be using:

300,000.00
300.000,00
300 000.00
300 000,00
300000.00
300000,00

Do you restrict, or give it hint, as to which are acceptable?