Here are various methods and techniques to check if a string is a number in JavaScript.
1. Using isNaN()
Method
The isNaN()
is a straightforward method in javascript check if string is number.
isNaN(num) // returns true if the variable does NOT contain a valid number
2. Using Number()
Function
You can also use the Number()
function to convert the input string into a number. If the input is a valid number, it will return that number; otherwise, it will return NaN
(which stands for “Not-a-Number”).
function isNumber(str) {
var num = Number(str);
if (!isNaN(num)) {
return true; // The input string is a number
} else {
return false; // The input string is not a number
}
}
console.log(isNumber("42")); // true
console.log(isNumber("3.14")); // true
console.log(isNumber("Hello")); // false
console.log(isNumber("123abc")); // false
3. Using TypeOf Expressions
let string1 = "test";
let string2 = "124";
function checkString(str){
if(typeof str === "string"){
console.log(!isNaN(string));
}
}
checkString(string1);
checkString(string2);

Our team of experienced developers is dedicated to sharing their knowledge and expertise with the community through engaging and informative articles and tutorials. We cover a wide range of topics, from the basics of JavaScript and React.js to advanced techniques for building modern web applications with Next.js.