数字输入中的千位分隔符,带有jQuery和regularexpressions

时间:2011-07-24 22:25:32

标签: jquery regex number-formatting

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

例如,当用户输入1000时,它应该转换为1 000,而不是他输入1 0000,并且它将被转换为10 000;删除最后一个零输入值应该返回1 000

有一个 jquery插件自动数字,但我只需要这千个分离功能

我的代码如下:

$('#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 ');

这一个未能删除最后一个号码

3 个答案:

答案 0 :(得分:5)

编辑:

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

答案 1 :(得分:0)

您可以使用:

var str = "1 2345 67 89  11";
str = str.replace(/\D+/g, '');
str = str.replace(/\d(?=(?:\d{3})+(?!\d))/g, '$& ');

http://jsfiddle.net/4Wsqq/

的示例

这个简单的解决方案不适用于负数或小数。

注意在keypress / keydown / keyup事件上执行此类操作时出现问题。我的主要烦恼是光标位置将移动到最后,这意味着用户无法在字符串末尾的任何其他位置输入/更改值。

答案 2 :(得分:0)

将数字分隔符类添加到您的输入文本元素并将代码添加到脚本中

<input type="text" class="number-separator" placeholder="Enter Your Number Here...">





jQuery(document).ready(function () {
jQuery(document).on('input', '.number-separator', function (e) {
if (/^[0-9.,]+$/.test($(this).val())) {
  $(this).val(
    parseFloat($(this).val().replace(/,/g, '')).toLocaleString('en')
  );
} else {
  $(this).val(
    $(this)
      .val()
      .substring(0, $(this).val().length - 1)
  );
}});});

您可以在以下位置查看示例: https://www.jqueryscript.net/demo/number-thousand-separator/