hash = window.location.hash.substr(1); var reg = new RegExp('^[0-9]$'); console.log(reg.test(hash));
I get false on both "123"
and "123f"
. I would like to check if the hash only contains numbers. Did I miss something?
Check if String Contains Only Numbers using isdigit() method Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It returns “False”.
\d for single or multiple digit numbers To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.
If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
var reg = /^\d+$/;
should do it. The original matches anything that consists of exactly one digit.
As you said, you want hash to contain only numbers.
const reg = new RegExp('^[0-9]+$');
or
const reg = new RegExp('^\d+$')
\d
and [0-9]
both mean the same thing. The + used means that search for one or more occurring of [0-9].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With