Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript parseInt when value = 0

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.

like image 772
frenchie Avatar asked Dec 21 '22 06:12

frenchie


2 Answers

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.

like image 97
Alex Wayne Avatar answered Jan 05 '23 06:01

Alex Wayne


You can use regular expressions:

var TheCleanInput = TheInput.replace(/\D/g, '');
like image 38
Ry- Avatar answered Jan 05 '23 07:01

Ry-