JavaScript isInteger Function
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); }
Like this? Follow me ↯
Tweet Follow @pfreitagJavaScript isInteger Function was first published on May 24, 2007.