Regex that matches integers in between whitespace or start/end of string only
All you want is the below regex:
^\d+$
Similar to manojlds but includes the optional negative/positive numbers:
var regex = /^[-+]?\d+$/;
EDIT
If you don't want to allow zeros in the front (023
becomes invalid), you could write it this way:
var regex = /^[-+]?[1-9]\d*$/;
EDIT 2
As @DmitriyLezhnev pointed out, if you want to allow the number 0
to be valid by itself but still invalid when in front of other numbers (example: 0
is valid, but 023
is invalid). Then you could use
var regex = /^([+-]?[1-9]\d*|0)$/
You could use lookaround instead if all you want to match is whitespace:
(?<=\s|^)\d+(?=\s|$)
This just allow positive integers.
^[0-9]*[1-9][0-9]*$
I would add this as a comment to the other good answers, but I need more reputation to do so. Be sure to allow for scientific notation if necessary, i.e. 3e4 = 30000. This is default behavior in many languages. I found the following regex to work:
/^[-+]?\d+([Ee][+-]?\d+)?$/;
// ^^ If 'e' is present to denote exp notation, get it
// ^^^^^ along with optional sign of exponent
// ^^^ and the exponent itself
// ^ ^^ The entire exponent expression is optional