Javascript check if string is number

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);

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top