我正在尝试实现一种场景,我可以将我的字符串限制为树数字,一个点和两个数字是点,最后两个数字是可选的。
例如:
- 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" />
最佳答案
尝试:
/^\d{1,3}(\.\d{1,2})?$/m;
使用 \d{1, 3}
你要求 1 到 3 位数字。使用 \.\d{1,2}
,您需要一个点,后跟 1 到 2 位数字。将前面的表达式放在 (...)?
中,使其成为可选的。
关于javascript - 我怎样才能使这个 "percentage-only"Regex 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28904532/