【问题标题】:How to check if a string is an int?如何检查字符串是否为int?
【发布时间】:2015-07-20 10:35:35
【问题描述】:

我有一个小 if 我想检查一个字符串,看看它是否是一个整数。我正在使用 JQuery 来执行此操作。

查询:

 var intRegex = /[0-9 -()+]+$/;


 if ($('#txtGRCSelect').val() != '' && intRegex($('#txtGRCSelect').val())) {
                        alert("No CASE");
                        $("#ErrorBoxText").html("Error : A Role has not been selected.");
                        rt = true;
                    }

它不起作用,谁能帮助我并告诉我为什么?

【问题讨论】:

  • @ArunPJohny 抱歉,忘记添加了,现在添加了
  • @nikhil 嗨,这也不起作用
  • 对于整数的正则表达式测试肯定应该更像/^[-+]?\d+$/?您当前的测试将验证 asdjhiujb2-(+)
  • @Phylogenesis 我根据建议更改了正则表达式,仍然没有得到任何结果
  • if (! /^[-+]?\d+$/.test($('#txtGRCSelect').val())) { /* Not a valid integer */ }。见this fiddle

标签: jquery string


【解决方案1】:

intRegex 是一个正则表达式对象,所以调用返回 true 的测试方法是字符串满足正则表达式

$('button').click(function() {
  var intRegex = /^[0-9 -()+]+$/; //may have to add `^` at the beginning to check the string is completely matches the regex, else it will just test whether the string ends with the given characters
  if ($('#txtGRCSelect').val() == '' || !intRegex.test($('#txtGRCSelect').val())) {
    alert("No CASE");
    $("#ErrorBoxText").html("Error : A Role has not been selected.");
    rt = true;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtGRCSelect" />
<button>Test</button>

【讨论】:

  • 嗨,我猜你的意思是“测试”方法?这也不起作用,因为它没有达到我的警报。
  • @ArunPJohny intRegex.text( 应该是 test(
【解决方案2】:
var ex=/^[0-9]*$/;
var A=$('#txtGRCSelect').val();
if(ex.test(A)==true)
{
alert("Value integer.");
}

【讨论】:

    【解决方案3】:

    方法一

    function IsNumeric(x){    
    var patt = new RegExp("^[0-9]+$");    
    return patt.test(x);
    }
    

    方法二

    function IsNumeric(x){
    x=x.replace('.','#');
    return!isNaN(parseFloat(x))&&isFinite(x);
    }
    

    示例:

    IsNumeric(1)
    

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 2016-03-29
      • 1970-01-01
      • 2011-11-25
      相关资源
      最近更新 更多