user20884192
user20884192

Reputation: 3

regular expression no more than one digit

how to make a regular expression into one number (only numbers) and that it does not exceed 10 from 0 to 10

/^[1-9][1]*$/.test(message)

It doesn't work that way for me.

Upvotes: 0

Views: 83

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

Assuming you only want integers or whole numbers, then use:

/^(?:[0-9]|10)$/

If you want to allow for decimals, then use:

/^(?:[0-9](?:\.\d+)?|10(?:\.0+)?)$/

The second regex says to match:

  • ^ from the start of the number
  • (?:
    • [0-9] 0 to 9
    • (?:\.\d+)? any optional decimal component
    • | OR
    • 10 match integer 10
    • (?:\.0+)? optional zero decimal only
  • )
  • $ end of the number

Upvotes: 0

Nasser Kessas
Nasser Kessas

Reputation: 361

To specify the amount of a specific character use {} instead of [], in this case, as it is only one digit, you do not need to specify a count as 1 is default:

/^[0-9]$/.test(message)

I assume you mean you want to match a single digit between 0 and 10. If not please comment to clarify.

Hope this helps.

Upvotes: 1

Related Questions