【问题标题】:Thousand separator in numeric input with jQuery and regularexpressions使用 jQuery 和正则表达式的数字输入中的千位分隔符
【发布时间】: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


【解决方案1】:

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

<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/

【讨论】:

    【解决方案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;
    }
    

    【讨论】:

    • 怎么样?它应该工作得很好。您遇到了什么错误?
    • @Ewout,如果您在除字符串 @“光标替换”结尾之外的任何地方添加/更改任何内容,则将不起作用。
    • @Qtax:再次同意,但总比没有好;-) OP 可能会研究 jQuery 的掩码插件之一。喜欢digitalbush.com/projects/masked-input-plugin。这些将产生所需的行为并将光标留在原处。
    • 这段代码并不完美:如果我选择数字的中间并编辑它,光标会跳到输入的末尾。 (jquery autonumberic 在这种情况下效果很好。)
    【解决方案3】:

    你可以使用:

    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 事件中执行此类操作会出现问题。我的主要烦恼是光标位置将移动到末尾,这意味着用户无法在字符串末尾之外的任何其他位置真正输入/更改值。

    【讨论】:

    • 不幸的是,它无法正常工作,但感谢您的帮助:) livemedical.net/exp.html
    • 什么不完全有效?它格式化数字对我来说很好。
    • 我按一 - 零 - 零 - 零 {HERE SHOUL BE SPACE 1 000} +zero => {10 000}, 'backspace' => {1 000} 已在此处上传您的代码:@ 987654323@
    • Backspace 不会触发该功能。使用您想要收听的正确事件。你可以看到它在按几次退格键后再次输入一个数字就可以工作了,它会重新格式化。
    • 嗯.. 为什么?退格键是一个键,它的代码在 jQuery (event.which = 8) api.jquery.com/keypress
    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    相关资源
    最近更新 更多