I'm using jquery.grep to clean a string and return only digits.
This is what I have:
var TheInputArray = TheInput.slice();
var TheCleanInput = jQuery.grep(TheInputArray, function (a) {
return parseInt(a, 10);
});
I take a string, split it into an array and use the parseInt function to check if it's a number. The problem is that when the value of a is 0, it skips that element. What changes do I need to do to make this code work?
Thanks.
Unfortunately, 0
in Javascript is falsy. So you need to be sure your return value is true
, even for a 0
.
var TheInputArray = TheInput.slice();
var TheCleanInput = jQuery.grep(TheInputArray, function (a) {
return ! isNaN(parseInt(a, 10));
});
parseInt
returns NaN
(not a number), if it fails to parse the input. And isNan()
will return true
if the argument is NaN
. So this should help you detect that case.
You can use regular expressions:
var TheCleanInput = TheInput.replace(/\D/g, '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With