jquery - 使用 jQuery 和正则表达式在数字输入中使用千位分隔符

标签 jquery regex number-formatting

我需要以这种模式输入数字:{1-3个数字} {white-space} {3个数字} {white-space} {3个数字} {white-space} ..等等..

例如,当用户输入 1000 时,应转换为 1 000,而输入 1 0000 时,则会转换为 10 000;删除最后一个零输入值应返回到 1 000

有一个jquery插件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 ');

此操作未能删除最后一个号码

最佳答案

编辑:

jsfiddle 上的工作示例

用于光标替换的猴子补丁示例:jsfiddle


来自代码SugarJS

/***
 * @method format([comma] = ',', [period] = '.')
 * @returns String
 * @short Formats the number to a readable string.
 * @extra [comma] is the character used for the thousands separator. [period] is the character used for the decimal point.
 * @example
 *
 *   (56782).format()           -> '56,782'
 *   (4388.43).format()         -> '4,388.43'
 *   (4388.43).format(' ')      -> '4 388.43'
 *   (4388.43).format('.', ',') -> '4.388,43'
 *
 ***/
'format': function(comma, period) {
  comma = comma || ',';
  period = period || '.';
  var split = this.toString().split('.');
  var numeric = split[0];
  var decimal = split.length > 1 ? period + split[1] : '';
  var reg = /(\d+)(\d{3})/;
  while (reg.test(numeric)) {
    numeric = numeric.replace(reg, '$1' + comma + '$2');
  }
  return numeric + decimal;
}

关于jquery - 使用 jQuery 和正则表达式在数字输入中使用千位分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6810171/

相关文章:

javascript - Jquery 如果在 2 个数字之间?

python - 如何用正则表达式替换多个重叠模式?

Java,提取$符号之间的单词

android - 在 Kotlin 中将值格式化为人类可读形式的依赖性

javascript - 如何在价格中添加尾随零?

javascript - 如何在不影响其他元素的情况下使用bootstrap collapse?

jquery - 使用 jQuery 提交数组的动态 HTML

c# - 使用 EPPLUS Excel 库格式化列

javascript - 如何检查带有 .Attr 的元素是否具有特定类?

Python 正则表达式 行内的任一/或