简体   繁体   English

用jquery和regex格式化正负十进制数

[英]Format positive and negative decimal numbers with jquery and regex

I found this code below at jsfiddle that, in my shitty opinion, is very nice. 我认为,我在下面的jsfiddle中发现了这段代码,它非常好。 But it doesn't format negative numbers, only positive. 但是它不会格式化负数,而只会格式化正数。 I tried to modify it but my regex knowledge wasn't enough. 我试图对其进行修改,但是我对正则表达式的了解还不够。 Could anyone help me modify this to format positive and negative numbers? 有人可以帮我修改此格式以设置正数和负数吗?

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

You could just check and see if the value is negative when you start, and add the sign back in at the end: 您可以在启动时检查值是否为负,然后在末尾添加符号:

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


EDIT: Here's a more "pure" regex solution: 编辑:这是一个更“纯”的正则表达式解决方案:

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

Basically, in the first replace statement, you add '-' to the set of characters to not get replaced, ie everything that isn't a digit or a dash will get replaced by '' in this new version. 基本上,在第一个replace语句中,将'-'添加到被替换的字符集中,即,在此新版本中,不是数字或破折号的所有内容都将替换为''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM