Home  >  Article  >  Web Front-end  >  How to determine whether the input is an integer using regular javascript

How to determine whether the input is an integer using regular javascript

藏色散人
藏色散人Original
2021-10-14 17:22:497011browse

javascript正则实现判断整数的方法:1、打开相应的js代码文件;2、通过“var r = /^\+?[1-9][0-9]*$/;String str = "123";boolean flag=r.test(str);”方法判断即可。

How to determine whether the input is an integer using regular javascript

本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

javascript正则如何判断输入是否是整数?

JS判断输入是否为整数的正则表达式

1、正则表达式

"^\\d+$"  //非负整数(正整数 + 0)
"^[0-9]*[1-9][0-9]*$"  //正整数
"^((-\\d+)|(0+))$"  //非正整数(负整数 + 0)
"^-[0-9]*[1-9][0-9]*$"  //负整数
"^-?\\d+$"    //整数
"^\\d+(\\.\\d+)?$"  //非负浮点数(正浮点数 + 0)
"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$"  //正浮点数
"^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$"  //非正浮点数(负浮点数 + 0)
"^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$"  //负浮点数
"^(-?\\d+)(\\.\\d+)?$"  //浮点数

2、使用方法

  var r = /^\+?[1-9][0-9]*$/;  //正整数
  String str = "123";
  boolean flag=r.test(str);

  如果判断为正整数,则flag为true

3、JS整数相加

  首先保证输入的都是数字

  nText1=parseFloat(document.all.text1.value);
  nText2=parseFloat(document.all.text2.value);
  nSum=nText1+nText2

推荐学习:《javascript基础教程

The above is the detailed content of How to determine whether the input is an integer using regular javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn