【发布时间】:2011-10-12 05:11:20
【问题描述】:
我需要在这种模式下输入数字:{1-3 numbers} {white-space} {3 numbers} {white-space} {3 numbers} {white-space} .. 等等..
例如,用户输入1000应该转换成1000,而不是输入10000,就会转换成10000;删除最后一个零输入值应返回 1 000
有一个jquery plugin autonumeric,但我只需要这个千位分隔函数
我的代码如下:
$('#myinput').live('keypress', function() {
if ($(this).val().length == 3){
newval = $(this).val().replace(/([0-9])([0-9]{2}$)/, '$1 $2');
}
if ($(this).val().length == 4){
newval = $(this).val().replace(/([0-9])([0-9]{3}$)/, '$1 $2');
}
...
$(this).val(newval);
});
它不能正常工作,还有这个:
newval = $(this).val().replace(/(\S{1,3})([$0-9]{2})/g, '$1 $2');
newval2 = newval.replace(/([0-9]{1})[\s]([0-9]{1})[\s]/g, '$1$2 ');
这个删除最后一个号码失败
【问题讨论】:
-
您可以使用这里给出的函数:mredkj.com/javascript/nfbasic.html 并在 while 循环中用空格替换逗号。
-
这个函数对我还是不起作用:function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '。' + x[1] : ''; var rgx = /(\d+)(\d{3})/;而 (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } 返回 x1 + x2; } $('#myinput').live('keypress', function(){ newval = addCommas($(this).val()); $(this).val(newval); });例如,它返回 1,0,0,0,000
标签: jquery regex number-formatting