使用正则表达式格式化文本输入货币模式

时间:2017-07-02 14:44:49

标签: javascript regex

我有文字输入,输入的格式为货币格式,如 1,000,500 。现在的问题是用户可以输入000.00, 0,0000,000, 000,438,339等数字。

我想知道是否有人可以帮我删除起始零的正则表达式,除非它采用这种格式0.00

如果我输入多个零而没有在第一个零之后放置小数点,例如000000那么它应该返回0.所以:

000.00 should be 0.00
0,0000,000 should be 0
000,438,339 should be 438,339

我这样做'0000.00'.replace(/^(00*)(.*)$/, '$2') id 并不涵盖所有边缘情况。

3 个答案:

答案 0 :(得分:0)

从字符串中删除逗号后,您可以使用/^0+(\d+(\.\d{1,2})?)$/;这包括您列出的三个案例:

'0,0000,000'.replace(/,/g, "").replace(/^0+(\d+(\.\d{1,2})?)$/, '$1')
// '0'

'000.00'.replace(/,/g, "").replace(/^0+(\d+(\.\d{1,2})?)$/, '$1')
// '0.00'

'000,438,339'.replace(/,/g, "").replace(/^0+(\d+(\.\d{1,2})?)$/, '$1')
// '438339'

答案 1 :(得分:0)

检查以下代码。一般的想法是首先检查输入值中是否有点符号。然后在点位置拆分值。如果条件i检查数字的第一部分(00.或000.或10.)是否被数字1除,然后结果不等于0.这就确保整数部分不是零。在此之后,如果条件我使用toLocaleString()方法为初始输入数字的第一部分重构值并重置输入值:



$('#myButton').on('click',function(){
  var currency=$('#myInput').val();
  var search=currency.indexOf(".");
  if(search){
    currency=currency.split(".");
    if((currency[0]/1)==0){
      currency[0]="0";     
     var newNum=currency[1].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      $('#myInput').val(currency[0]+"."+newNum);
    }else{
      var newNum=currency[1].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      $('#myInput').val(Math.round(parseInt(currency[0]))+"."+newNum);
    }
   }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" />
  <button id="myButton">Get Currency</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

下面评论的代码段有效地说明了您想要实现的目标;该函数将您给定的值格式化为所需的格式。

&#13;
&#13;
// Defining input cases variable.
var caseOne = '000.00';
var caseTwo = '00,0000,000';
var caseThree = '000,438,339';

// Assigning a given case to the someAmount variable (any of the cases above).
// For the purpose of this illustration, we assigned caseThree as value to someAmount.
var someAmount = caseThree;

// formatInput function (to format the given input case).
function formatInput(amountToFormat) {
    if (amountToFormat.match(/^0*(\.)(0*)$/)) {
        console.log('0'.concat(amountToFormat.replace(/^0*(\.)(0*)$/, '$1' + '$2')));
    }
    if (amountToFormat.match(/^0*(\,)([0-9]+)(\,)([0-9]+)$/)) {
        var blockTwo = amountToFormat.replace(/^0*(\,)(0*)(\,)(0*)$/, '$2');
        var blockFour = amountToFormat.replace(/^0*(\,)(0*)(\,)(0*)$/, '$4');
        if (eval(blockTwo) != 0 && eval(blockFour) != 0) {
            console.log(amountToFormat.replace(/^0*(\,)([0-9]+)(\,)([0-9]+)$/, '$2' + '$3' + '$4'));
        } else {
            console.log('0');
        }
    }
}

// Use the formatInput function where needed by passing in the value
// of the input to be formatted as someAmount.
// Expected outputs:
// 0.00 for caseOne, 0 for caseTwo, and 438,339 for caseThree.

formatInput(someAmount);
// Expected output for the purpose of this illustration: 438,339
&#13;
&#13;
&#13;