How can I do this regex "percent only"?

I am trying to create a scenario where I can limit my string to the tree digits with one dot, and the two digits with a dot, and the last two digits are optional.

eg:

  • 100.00
  • 1
  • 10.56
  • 31.5

I could get a regular expression that would allow me to avoid others except the dot and semicolon, and remove the extra points.

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;
}

I tried the following regular expression based on knowledge of the regular expression (if it can be considered any ...)

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

But now it does not show any errors and does not work at all.


I use this function in jQuery(document).on('focusout',, jQuery(document).on('paste',and jQuery(document).on('keyup',(I separated them so that everything was ready)

Excerpt

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" />
Run codeHide result
+4
1

Try:

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

\d{1, 3} 1 3 . \.\d{1,2} , 1 2 . (...)?, .

+3

All Articles