Zlatan Omerovic
Zlatan Omerovic

Reputation: 4097

How to force parseInt to return NaN on any string occourence?

For example if we say:

parseInt("128"); // => 128

Works flawlessly.

If we say:

parseInt("a128"); // => NaN

But if we say:

parseInt("123a"); // => 128 again :(

Is there an explicit way to parse the number only and if any alphabet character appears in the argument, it would return NaN?

Upvotes: 1

Views: 563

Answers (4)

Deep
Deep

Reputation: 9794

for your scenario where you need to deal with string you can use Number function as well.Number() function converts the object argument to a number that represents the object's value

   
//test cases
console.log( Number("123") );
console.log( Number("123a") );
console.log( Number("a123") );

Upvotes: 2

user5730329
user5730329

Reputation:

You can do the function yourself as well:

function in_array (array, key){
    var check = false;
    for(var i = 0; i < array.length; i++){
        if(key == array[i]){
            check = true;
            break;
        }
    }
    return check;
}

var allowedchars=["0","1","3","4","5","6","7","8","9"];

function checkIsStringNaN (str){
    var b = true;
    for(var i = 0, i < str.length; i++){
        if(!in_array(allowedchars, str.charAt(i))){
            b = false;
            break;
        }
    }
    if(!b) {
        return NaN;
    } else {
        return parseInt(str);
    }
}

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68413

parseInt doesn't work this way, check the specs.

  1. It removes leading and trailing spaces.
  2. If a character is encountered which isn't interpreted as integer and isn't supported by radix, then it is ignored

However you can force it work this way by doing

    (function(){
            var old = parseInt;
            parseInt = function(x, y){
                if ( ( !y || y == 10 ) && isNaN( Number(x) ) ) { return NaN }
                return old.apply(this, arguments)
            }
    })();

//test cases
console.log( parseInt("123") );
console.log( parseInt("123a") );
console.log( parseInt("123a", 16) );
console.log( parseInt("a123") );

Upvotes: 2

Oskar Szura
Oskar Szura

Reputation: 2569

Is that what you expect to have?

function checkIsStringNaN (str) {
  return isNaN(str) ? NaN : parseInt(str)
}

checkIsStringNaN("128") // 128
checkIsStringNaN("a128") // NaN
checkIsStringNaN("123a") // NaN

Upvotes: 0

Related Questions