8

This is a solution for validating an integer. Can someone please explain the logic of Karim's answer.
This works perfectly, but i am not able to understand how.

var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
   alert('I am an int');
   ...
}
2
  • 1
    I think this question should better be a comment on that answer… and should be answered there by @Karim himself. Commented Jun 5, 2013 at 13:55
  • 3
    Note that this code is not entirely correct. For example, it validates a string like 000...(10,000 times)..000 which is hardly a "number". Commented Jun 5, 2013 at 13:58

4 Answers 4

16

The regex: /^\d+$/

^ // beginning of the string
\d //  numeric char [0-9]
+ // 1 or more from the last
$ // ends of the string

when they are all combined:

From the beginning of the string to the end there are one or more numbers char[0-9] and number only.

Sign up to request clarification or add additional context in comments.

Comments

6

Check out a Regular Expression reference: http://www.javascriptkit.com/javatutors/redev2.shtml

/^\d+$/
^ : Start of string
\d : A number [0-9]
+ : 1 or more of the previous
$ : End of string

Comments

0

What is a Nonnegative Whole Number?

A Nonnegative whole number is an "integer that is either 0 or positive."

Source: http://mathworld.wolfram.com/NonnegativeInteger.html

In other words, you are looking to validate a nonnegative integer.

The answers above are insufficient because they do not include integers such as -0 and -0000, which, technically, after parsing, become nonnegative integers. The other answers also do not validate integers with + in front.

You can use the following regex for validation:

/^(\+?\d+|-?0+)$/

Try it Online!

Explanation:

^                   # Beginning of String
    (               # Capturing Group
            \+?     # Optional '+' Sign
            \d+     # One or More Digits (0 - 9)
        |           # OR
            -?      # Optional '-' Sign
            0+      # One or More 0 Digits
    )               # End Capturing Group
$                   # End of String

The following test cases return true: -0, -0000, 0, 00000, +0, +0000, 1, 12345, +1, +1234. The following test cases return false: -12.3, 123.4, -1234, -1.

Note: This regex does not work for integer strings written in scientific notation.

Comments

-1

This regex may be better /^[1-9]+\d*$/

^     // beginning of the string
[1-9] // numeric char [1-9]
+     // 1 or more occurrence of the prior
\d    // numeric char [0-9]
*     // 0 or more occurrences of the prior
$     // end of the string

Will also test against non-negative integers that are pre-padded with zeroes

1 Comment

This will fail on '0'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.