我怎样才能使这个“仅百分比”正则表达式工作?

时间:2015-03-06 17:42:46

标签: javascript jquery regex string

我试图实现一种方案,我可以将字符串限制为树形数字一个点,两个数字是点,最后两个数字是可选的。

例如:

  • 100.00
  • 1
  • 10.56
  • 31.5

我可以实现一个正则表达式,允许我除了点和逗号之外还可以避免其他的,并删除多余的点。

function isPercentage(input){
    var regex = /[^0-9\.]/g;

    var value = input.replace(regex, '');
    var index = value.indexOf( '.' );
    if ( index > -1 ) {
        value = value.substr( 0, index + 1 ) +
        value.slice( index ).replace( /\./g, '' );
    }
    return value;
}

我根据正则表达式的知识尝试了以下正则表达式(如果它可以被认为是......)

var regex = /^[0-9]{3}\.{1}[0-9]{2}$/g;

但现在它没有显示任何错误,也没有任何效果。


我在jQuery(document).on('focusout',jQuery(document).on('paste',jQuery(document).on('keyup',中使用此功能(我将它们分开以便于准备)

片段



jQuery(document).ready(function(){
  jQuery(document).on('focusout','.decimal_only', function(){
    jQuery(this).val(isPercentage(jQuery(this).val()));
  });
  
  jQuery(document).on('paste','.decimal_only', function(){
    var element = jQuery(this);
    setTimeout(function () {
      var v = element.val();
      element.val(isPercentage(v));
    }, 100);
  });
  
  jQuery(document).on('keyup','.decimal_only', function(){
    var kc = event.keyCode;
		var cmdKeys = [9,13,16,17,18,19,20,27,33,34,35,36,37,38,39,40,45,91,92,93,96,97,98,99,100,101,102,103,104,105,112,113,114,115,116,117,118,119,120,121,122,123,144,145];
		if(jQuery.inArray(kc,cmdKeys) == -1) {
			jQuery(this).val(isPercentage(jQuery(this).val()));
		}
	});
});

function isPercentage(input){
  var regex = /[^0-9\.]/g;

  var value = input.replace(regex, '');
  var index = value.indexOf( '.' );
  if ( index > -1 ) {
    value = value.substr( 0, index + 1 ) +
      value.slice( index ).replace( /\./g, '' );
  }
  return value;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="decimal_only" />
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

尝试:

/^\d{1,3}(\.\d{1,2})?$/m;

使用\d{1, 3},您需要1到3位数字。使用\.\d{1,2},您需要一个点后跟1到2位数字。将前一个表达式放在(...)?中,可以使它成为可选项。