【问题标题】:Format positive and negative decimal numbers with jquery and regex使用 jquery 和 regex 格式化正负十进制数
【发布时间】:2017-07-10 17:39:55
【问题描述】:

我在下面的jsfiddle 找到了这段代码,在我看来,这非常好。 但它不格式化负数,只有正数。 我试图修改它,但我的正则表达式知识还不够。 谁能帮我修改它以格式化正数和负数?

$('#valor').keyup(function(){
    var v = $(this).val();
    v = v.replace(/\D/g,'');
    v = v.replace(/(\d{1,2})$/, ',$1');  
    v = v.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');  
    v = v != '' ? 'R$ '+ v : '';
    $(this).val(v); 
});

【问题讨论】:

    标签: javascript jquery regex currency number-formatting


    【解决方案1】:

    您可以在开始时检查该值是否为负,然后在末尾添加符号:

    $('#valor').keyup(function(){
        let v = $(this).val();
        const neg = v.startsWith('-');
    
        v = v.replace(/[-\D]/g,'');
        v = v.replace(/(\d{1,2})$/, ',$1');
        v = v.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
    
        v = v != ''?'$ '+v:'';
        if(neg) v = '-'.concat(v);  // prepend the dash
    
        $(this).val(v);
    });
    

    jsfiddle


    编辑:这是一个更“纯”的正则表达式解决方案:

    $('#valor').keyup(function(){
        let v = $(this).val();
    
        v = v.replace(/[^-\d]/g, '');
        v = v.replace(/(\d{1,2})$/g, ',$1');
        v = v.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
    
        v = v ? '$ ' + v : '';
        $(this).val(v);
    
    });
    

    jsfiddle

    基本上,在第一个替换语句中,您将'-' 添加到字符集以 被替换,即所有不是数字或破折号的内容都将被@987654326 替换@ 在这个新版本中。

    【讨论】:

    • 这解决了问题,但我想知道如何用正则表达式解决这个问题,因为它对我来说看起来更优雅。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 2013-07-29
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多