Surf 11 » JavaScript isInteger Function

Finding the best waves on the web.

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


Related Entries
On 01/02/2013 at 12:00:00 AM UTC dandavis wrote:
1
here is a 5-10X faster version:

function isInteger(s){return parseInt(s,10)===s;}

Name:

Email: (optional, not displayed on site)
   Subscribe to this thread
Comments: (html will be escaped)



Subscribe to our RSS Feed: subscribe to this feed XML
Archives   Tags   Contact