验证字符串是否为正整数 [英] Validate that a string is a positive integer

查看:121
本文介绍了验证字符串是否为正整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望最简单的故障安全测试来检查JavaScript中的字符串是否为正整数。

I would like the simplest fail-safe test to check that a string in JavaScript is a positive integer.

isNaN(str)为所有种类的非整数值返回true, parseInt(str)返回浮点字符串的整数,如2.5。而且我也不想使用一些jQuery插件。

isNaN(str) returns true for all sorts of non-integer values and parseInt(str) is returning integers for float strings, like "2.5". And I don't want to have to use some jQuery plugin either.

推荐答案

两个答案:


  • 基于解析

  • Based on parsing

正则表达式

请注意,在这两种情况下,我都将正整数解释为包含 0 ,即使 0 不是正面的。如果你想禁止 0 ,我会附上备注。

Note that in both cases, I've interpreted "positive integer" to include 0, even though 0 is not positive. I include notes if you want to disallow 0.

如果您希望它是一个合理范围的值的标准化十进制整数字符串,您可以这样做:

If you want it to be a normalized decimal integer string over a reasonable range of values, you can do this:

function isNormalInteger(str) {
    var n = Math.floor(Number(str));
    return n !== Infinity && String(n) === str && n >= 0;
}

实时测试平台:

function isNormalInteger(str) {
    var n = Math.floor(Number(str));
    return String(n) === str && n >= 0;
}
function gid(id) {
  return document.getElementById(id);
}
function test(str, expect) {
  console.log(str + ": " + (isNormalInteger(str) ? "Yes" : "No"));
}
gid("btn").addEventListener(
  "click",
  function() {
    test(gid("text").value);
  },
  false
);
test("1");
test("1.23");
test("1234567890123");
test("1234567890123.1");

<label>
  String:
  <input id="text" type="text" value="">
<label>
<input id="btn" type="button" value="Check">

如果你想禁止 0 ,只需将> = 0 更改为> 0

If you want to disallow 0, just change >= 0 to > 0.

如何运作:


  1. Number(str):将 str 转换为数字;该数字可能有一小部分,或者可能 NaN

  1. Number(str): Convert str to a number; the number may well have a fractional portion, or may be NaN.

Math.floor :截断数字(截断任何小数部分)。

Math.floor: Truncate the number (chops off any fractional portion).

String(。 ..):将结果转换回普通的十进制字符串。对于非常大的数字,这将采用科学记数法,这可能会破坏这种方法。 (我不太清楚分裂的位置,详细信息在规范中,但对于整数,我相信它已超过21位[此时数字变得非常不精确,因为IEEE- 754双精度数字只有15位精度..)

String(...): Converts the result back into a normal decimal string. For really big numbers, this will go to scientific notation, which may break this approach. (I don't quite know where the split is, the details are in the spec, but for whole numbers I believe it's at the point you've exceeded 21 digits [by which time the number has become very imprecise, as IEEE-754 double-precision numbers only have roughtly 15 digits of precision..)

... === str :将其与原始字符串进行比较。

... === str: Compares that to the original string.

n> = 0 :检查这是积极的。

请注意输入+ 1,科学记数法中的任何输入都不会在 String(...)阶段转回相同的科学记数法,以及任何值JavaScript使用的数字种类(IEEE-754双精度二进制浮点数)不能准确地表示哪个解析更接近于给定的一个不同的值(我包括超过9,007,199,254,740,992的许多整数;例如, 1234567890123456789 将失败)。前者是一个简单的修复,后两个不是很多。

Note that this fails for the input "+1", any input in scientific notation that doesn't turn back into the same scientific notation at the String(...) stage, and for any value that the kind of number JavaScript uses (IEEE-754 double-precision binary floating point) can't accurately represent which parses as closer to a different value than the given one (which includes many integers over 9,007,199,254,740,992; for instance, 1234567890123456789 will fail). The former is an easy fix, the latter two not so much.

另一种方法是如果你的目标只是允许(比方说)一个可选的 + ,然后是 0,那么通过正则表达式测试字符串的字符或普通十进制格式的字符串:

The other approach is to test the characters of the string via a regular expression, if your goal is to just allow (say) an optional + followed by either 0 or a string in normal decimal format:

function isNormalInteger(str) {
    return /^\+?(0|[1-9]\d*)$/.test(str);
}

实时测试平台:

function isNormalInteger(str) {
    return /^\+?(0|[1-9]\d*)$/.test(str);
}
function gid(id) {
  return document.getElementById(id);
}
function test(str, expect) {
  console.log(str + ": " + (isNormalInteger(str) ? "Yes" : "No"));
}
gid("btn").addEventListener(
  "click",
  function() {
    test(gid("text").value);
  },
  false
);
test("1");
test("1.23");
test("1234567890123");
test("1234567890123.1");

<label>
  String:
  <input id="text" type="text" value="">
<label>
<input id="btn" type="button" value="Check">

如何运作:


  1. ^ :匹配字母串的开头

\ +?:允许一个可选的 + (如果你不想删除它)

\+?: Allow a single, optional + (remove this if you don't want to)

(?:... | ...):允许这两个选项中的一个(不创建捕获group):

(?:...|...): Allow one of these two options (without creating a capture group):


  1. (0 | ...):允许 0 独自......

  1. (0|...): Allow 0 on its own...

(... | [ 1-9] \d *):...或以 0 以外的其他数字开头的数字,后跟任意数量的小数位。

(...|[1-9]\d*): ...or a number starting with something other than 0 and followed by any number of decimal digits.


  • $ :匹配字符串结尾。

    如果你想禁止 0 (因为它是正面)正则表达式只是 / ^ \ +?[1-9] \d * $ / (例如,我们可能会失去我们需要允许的替换 0 )。

    If you want to disallow 0 (because it's not positive), the regular expression becomes just /^\+?[1-9]\d*$/ (e.g., we can lose the alternation that we needed to allow 0).

    如果你想允许前导零(0123, 00524),然后用 \d + (?: 0 | [1-9] \d *) $ c>

    If you want to allow leading zeroes (0123, 00524), then just replace the alternation (?:0|[1-9]\d*) with \d+

    function isNormalInteger(str) {
        return /^\+?\d+$/.test(str);
    }
    

    注意将它转换为数字:在现代引擎上它可能可以使用 + str Number(str)来执行此操作,但较旧的可能会扩展为非-standard(但以前允许)的方式表示前导零意味着 octal (基数为8),例如010=> 8.一旦验证了数字,就可以安全地使用 parseInt(str,10)以确保它被解析为十进制(基数为10)。 parseInt 会忽略字符串末尾的垃圾,但我们确保没有任何正则表达式。

    Note for when you convert that to a number: On modern engines it would probably be fine to use +str or Number(str) to do it, but older ones might extend those in a non-standard (but formerly-allowed) way that says a leading zero means octal (base 8), e.g "010" => 8. Once you've validated the number, you can safely use parseInt(str, 10) to ensure that it's parsed as decimal (base 10). parseInt would ignore garbage at the end of the string, but we've ensured there isn't any with the regex.

    这篇关于验证字符串是否为正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆