RegExp range of number (1 to 36)
You know about \d
, right?
^([1-9]|[12]\d|3[0-6])$
Try this in console:
function test() {
for(var i = 0; i < 100; i++) {
if (/^([1-9]|[12]\d|3[0-6])$/.test(i.toString()) != (i >= 1 && i <=36)) {
document.write(i + "fail");
}
else
document.write(i + "pass");
document.write("<br/>");
}
}
^(?:[1-9]|[1-2][0-9]|3[0-6])$
Here's a breakdown of it:
^
= Start of line
(?:
and )
demark a non-capturing group- a way to specify order of operations without saving the matched contents for later.
[1-9]
= any digit from 1-9
|
= OR
[1-2][0-9]
= '1' or '2', followed by any digit from 0-9
|
= OR
3[0-6]
= '3', followed by any digit from 0-6.
$
= end of line
As @mu is too short said, using an integer comparison would be a lot easier, and more efficient. Here's an example function:
function IsInRange(number)
{
return number > 0 && number < 37;
}
Try this:
^[1-9]$|^[1-2][0-9]$|^3[0-6]$
(All 1 digit numbers between 1 and 9, all 1x and 2x numbers, and 3x numbers from 30 to 36).