JavaScript int.TryParse Equivalent

14. January 2008

One of the most handy methods in .NET is the int.TryParse method. It makes it really convenient when evaluating a string value as an integer. But, JavaScript has no equivalent so you need to do your own evaluation every time.

Here's a simple JavaScript method I wrote that takes the work out of evaluating a string to an integer:

The first parameter of the TryParseInt method is the string you want to evaluate, and the second parameter is the default value to return if the string cannot be evaluated to an integer.

Here are some example usages:

General



Comments

1/15/2008 10:03:00 AM #
... isNaN("") == false and parseInt("") == NaN...

So, a better test would be (null and undefined values of str will result in false):
function TryParseInt(str, defaultValue) {
    return /^\d+$/.test(str) ? parseInt(str) : defaultValue;
}
Comments are closed