Forum Moderators: open
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>
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.
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