validate a string is non-negative whole number in javascript

12,174

Solution 1

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.

Solution 2

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
Share:
12,174
Lalithesh
Author by

Lalithesh

Updated on August 13, 2022

Comments

  • Lalithesh
    Lalithesh over 1 year

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