Reputation: 4097
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
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
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
Reputation: 68413
parseInt
doesn't work this way, check the specs.
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
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