Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To check string is a number in javascript, use "+" unary operator to convert the string to a number and check converted value is not a "NaN" and that a datatype is a number if both are true then your string is a number.

Use Number.isInteger() method to check converted number is a integer. ( *** The isInteger() method true only for integer numbers not for decimal number *** )

Today, I’m going to show you How do I check string is a number or an integer in javascript, as mentioned above, I’m going to do create two functions first to check string is a number and second, to check string is an integer.

Let’s start today’s tutorial on how do you check string is a number or an integer in javascript.

Javascript check string is a number

Here, we will do

  1. Create a function isNumber() and validate string param is a number
  2. If the param is a number return true else false.
function isNumber(param) {
    // convert string to number
    const num = +param;
    
    // validate is converted value is number
    return !Number.isNaN(num);
}

// true
console.log(isNumber("8932"))

// true
console.log(isNumber("8932.8493"))

// false
console.log(isNumber("8932.8493af"))

Output

Javascript check string is an integer

Here, we will do

  1. Create a function isInteger() and validate string param is an integer or not
  2. If the param is an integer return true else false.
function isInteger(param) {
    // convert string to number
    const num = +param;
    
    // validate is converted value is number
    return Number.isInteger(num);
}

// true
console.log(isInteger("8932"))

// false
console.log(isInteger("8932.8493"))

// false
console.log(isInteger("8932.8493af"))

Output

I hope it helps you, All the best đź‘Ť.