Pete Freitag Pete Freitag

JavaScript isInteger Function

Published on May 24, 2007
By Pete Freitag

It is pretty common that you need to check for an integer in javascript validation code. Here's a simple javascript isInteger function code examples.

function isInteger(s) {
  return (s.toString().search(/^-?[0-9]+$/) == 0);
}

Two things to note about our isInteger function. The first is that we are calling the javascript toString() function / method to convert the value to a string, so we can perform the regular expression. The second is that the regular expression allows for negative integers (since by definition an integer can be negative), if you want an unsigned isInt function try the following:

function isUnsignedInteger(s) {
  return (s.toString().search(/^[0-9]+$/) == 0);
}

JavaScript isInteger Function was first published on May 24, 2007.

Discuss / Follow me on Twitter ↯

Post a Comment