Validate string - non-negative integer in javascript

This is a solution for checking an integer. Can someone explain Karim's logic to answer . This works fine, but I can't figure out how to do this.

var intRegex = /^\d+$/; if(intRegex.test(someNumber)) { alert('I am an int'); ... } 
+5
javascript regex validation integer
Jun 05 '13 at 13:35
source share
4 answers

Regular expression: /^\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:

At the beginning of the line to the end, there is one or more char [0-9] numbers and only a number.

+11
Jun 05 '13 at 13:37
source share

Check out the regex link: 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 
+5
Jun 05 '13 at 13:37
source share

What is a non-negative integer?

A A non-negative integer is "an integer that is either 0 or positive."

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

In other words, you want to check for a non-negative integer.

There are not enough answers because they do not include integers, such as -0 and -0000 , which technically become non-negative integers after parsing. Other answers also do not confirm integers with + in front.

You can use the following regular expression to test:

 /^(\+?\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 regular expression does not work for whole lines written in scientific notation.

0
Feb 27 '18 at 1:45
source share

This regular expression 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 be checked for non-negative integers that are prefilled with zeros

-one
Nov 07 '14 at 9:37
source share



All Articles