regex only number not exceed 1000 except 0 in javascript

To regex only numbers that do not exceed 1000 and exclude 0 in JavaScript, you can use the following regular expression:

index.tsx
/^(?!0$)(?!0\d)([1-9]|[1-9]\d|1000)$/
38 chars
2 lines

Let's break it down:

  • ^ asserts the start of the string
  • (?!0$) negative lookahead to exclude just a single '0'
  • (?!0\d) negative lookahead to exclude '0' followed by any digit
  • ([1-9]|[1-9]\d|1000) matches either a single digit from 1 to 9, or two digits from 10 to 99, or 1000
  • $ asserts the end of the string

Here's how you can use this regular expression in JavaScript:

index.tsx
const regex = /^(?!0$)(?!0\d)([1-9]|[1-9]\d|1000)$/;
const number1 = "50";
const number2 = "100";
const number3 = "999";
const number4 = "1000";
const number5 = "0";
const number6 = "1001";

console.log(number1.match(regex)); // ["50"]
console.log(number2.match(regex)); // ["100"]
console.log(number3.match(regex)); // ["999"]
console.log(number4.match(regex)); // ["1000"]
console.log(number5.match(regex)); // null
console.log(number6.match(regex)); // null
461 chars
15 lines

In the above code snippet, we create a regular expression object using the RegExp constructor and test it against various numbers using the match method. Only numbers that match the regular expression are returned and all others return null.

gistlibby LogSnag