There are a couple of ways that we can use JavaScript to check if a string is a number. We will start with one of the easiest ways which is to use the JavaScript isNaN() method.
var stringNum = "1234";
console.log(isNaN(stringNum));
#Output
false
The isNAN() method stands for is “Not a Number”. So in our example, since the isNaN(stringNum)
returns false, it means that our string, “1234”, IS a number.
Let’s see some more examples of this method in use:
var variable1 = "12.34";
var variable2 = "1,290";
var variable3 = "-23";
var variable4 = "0034";
var variable5 = ".0034";
var variable6 = "$100";
var variable7 = "50%";
console.log(isNaN(variable1));
console.log(isNaN(variable2));
console.log(isNaN(variable3));
console.log(isNaN(variable4));
console.log(isNaN(variable5));
console.log(isNaN(variable6));
console.log(isNaN(variable7));
#Output:
false
true
false
false
false
true
true
Using the JavaScript Number() Method to Check If String is a Number
We can also use the JavaScript Number() method to check if a string is a number. The Number() method takes a string and either returns the string as a number, which means the string is a number, or it returns NaN.
var stringNum = "1234";
console.log(Number(stringNum));
#Output
1234
We can put this code into an if-else conditional statement to have it return true or false.
var stringNum = "1234";
if (Number(str)) {
//String IS a number
} else {
//String is not a number
}
Finally, we can put this code in a function.
function isNumber(str){
if (Number(str)) {
return true;
} else {
return false;
}
}
Now let’s see it in use with the same examples from above. Since our function is checking if the String IS a number, it should produce the opposite results from the isNaN() method.
function isNumber(str){
if (Number(str)) {
return true;
} else {
return false;
}
};
var variable1 = "12.34";
var variable2 = "1,290";
var variable3 = "-23";
var variable4 = "0034";
var variable5 = ".0034";
var variable6 = "$100";
var variable7 = "50%";
console.log(isNumber(variable1));
console.log(isNumber(variable2));
console.log(isNumber(variable3));
console.log(isNumber(variable4));
console.log(isNumber(variable5));
console.log(isNumber(variable6));
console.log(isNumber(variable7));
#Output:
true
false
true
true
true
false
false
Hopefully this article has been useful for you to learn how to use JavaScript to check if a string is a number.