0

should be simple but RegExs never seem to be :). Can anyone help on how to strip both a comma and any non-numeric characters from a string? Thanks. It's in the var result block. Apparently when you put an operator in the number it bombs out.num1 and num2. I also need to strip out any dashes.

 function calcTotalRetailVal() {
    var num1 = $oneTimeCostField.val();
    var num2 = $recurringTotalCostField.val();
   //In the replace method
    var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
    if (!isNaN(result)) {
        $totalRetailAmountField.text('$' + result.toFixed(2));
    }   
}

3 Answers 3

4
const clearText = plainText.replace(/\D/g,'')

\D will match all non-digits, but if you need to preserve dots and dashes:

replace(/[^\d.-]/g, '')
Sign up to request clarification or add additional context in comments.

5 Comments

This will also remove a minute sign, which is needed for negative numbers, and the decimal point.
Thank you, i also need to strip the dash b/c of the case of someone putting in a negative amount.
replace(/[^\d.]/g, '') then
I also need to remove commas (sorry to keep bothering)
replace(/[^\d,-]/g, '') this Will strip dashes an commas
1

You should use this regex /(,|[^\d.-]+)+/g to detect comma and any non-numeric value such as characters, operators, spaces in the groups and faster than the individual detection. a negative number (ex -1) and . will be included.

I rewrite your code.

function calcTotalRetailVal() {
    var num1 = $oneTimeCostField.val();
    var num2 = $recurringTotalCostField.val();
   //In the replace method
    var result = parseFloat(num1.replace(/(,|[^\d.-]+)+/g, '')) + parseFloat(num2.replace(/(,|[^\d.-]+)+/g, ''));
    if (!isNaN(result)) {
        $totalRetailAmountField.text('$' + result.toFixed(2));
    }   
}

Comments

1

With a regexp. num1.replace(/[^0-9.]/, '')

1 Comment

You should also allow a minute sign for negative numbers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.