hash = window.location.hash.substr(1);
var reg = new RegExp('^[0-9]$');
console.log(reg.test(hash));

“123”和“123f”都是假的。我想检查哈希是否只包含数字。我错过什么了吗?


当前回答

只有数字的正则表达式(已更新)

 var reg = new RegExp('[^0-9]','g');

其他回答

如果你只需要正整数而不需要前导零(例如。"0001234"或"00"):

var reg = /^(?:[1-9]\d*|\d)$/;

你需要*,所以它表示“零或多个前一个字符”,这应该做到:

var reg = new RegExp('^\\d*$');

如果数字不是特别大,可以用:

new RegExp(
    '^' +                           // No leading content.
    '[-+]?' +                       // Optional sign.
    '(?:[0-9]{0,30}\\.)?' +         // Optionally 0-30 decimal digits of mantissa.
    '[0-9]{1,30}' +                 // 1-30 decimal digits of integer or fraction.
    '(?:[Ee][-+]?[1-2]?[0-9])?' +   // Optional exponent 0-29 for scientific notation.
    '$'                             // No trailing content.
)

这试图避免一些场景,以防万一:

溢出原始字符串可能传递到的任何缓冲区。 由1E-323等非正常数字引起的缓慢或异常。 当期望有一个有限的数字时通过无穷大(尝试1E309或-1E309)。

您也可以使用以下方法,但要注意它们的内部实现和/或返回值。

1A isNaN(+'13761123123123'); // returns true
1B isNaN(+'13761123123ABC'); // returns false

2A ~~'1.23'; // returns 1
2B ~~'1.2A'; // returns 0

For 1A & 1B the string is first type coerced using the + operator before being passed to the isNaN() function. This works because a number types that include non-numeric values return NaN. There are considerations with the isNaN()'s implementation details which is documented here. One consideration is if a boolean value is passed as isNaN(+false|true) are coerced to their numeric equivalents and thus false is returned but one might expect the function to return true since the boolean value isn't numeric in the sense of what we are testing.

对于2A和2B,值得注意的是,寻找数字的补数要求给定的值在规范中可以引用的32位有符号整数的值范围内。

我个人的偏好是1A和1B,因为它们包含一元运算符,因此可读性较差,因为速度和简洁。

穿孔https://jsperf.com/numeric-string-test-regexvsisnan/1

var pattern = /[0-9!"£$%^&*()_+-=]/;

这试图避免一些场景,以防万一:

溢出原始字符串可能传递到的任何缓冲区。 由1E-323等非正常数字引起的缓慢或异常。 当期望有一个有限的数字时通过无穷大(尝试1E309或-1E309)。