Sotiris Sotiris - 1 month ago 17
Javascript Question

Check a range of numbers in an if condition

I wonder if it possible to use in

if
statement regex. I want to check if a value is in an accepted range. If yes to do something otherwise something else.

The range is
0.001-0.009
. I know how to use multiple
if
to check this, but I want to know if there is any way to check it in a single
if
statement with regex.

Answer

You're asking a question about numeric comparisons, so regular expressions really have nothing to do with the issue. You don't need "multiple if" statements to do it, either:

if (x >= 0.001 && x <= 0.009) {
  // something
}

You could write yourself a "between()" function:

function between(x, min, max) {
  return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
  // something
}