JS on yellow background

JavaScript: how to check if a string variable is an integer value

Written by

in

In JavaScript, one way to check if a variable is of type integer, Number.isInteger() can be used:

JavaScript
Number.isInteger(22); // true
Number.isInteger(22.2); // false
Number.isInteger('22'); // false

But this solution has the disadvantage, that a string with integer value like '22' will result in false.

Use parseInt

You can use the parseInt function to parse a string and convert it into an integer. If the string represents a valid integer, parseInt will return that integer value. If not, it will return NaN (Not a Number). You can then check if the result is a number or not to determine if the string represents an integer. Here’s how you can achieve it:

JavaScript
function isInteger(value) {
  return +value === parseInt(value);
}

isInteger(22); // true
isInteger(22.2); // false
isInteger('22'); // true

This will result in true for integer 22 as well as an integer “string” '22'.

Use regular expression

JavaScript
function isInteger(value) {
  // Use regular expression to check if the value consists only of digits
  return /^\d+$/.test(value);
}

isInteger(22); // true
isInteger(22.2); // false
isInteger('22'); // true

This function isInteger checks if the string consists only of digits (0-9) using a regular expression. If it consists only of digits, it returns true, indicating that the string represents an integer value; otherwise, it returns false.


Comments

Leave a Reply

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