2017-07-02 78 views
0

我有文本輸入時,它以貨幣格式輸入它像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不覆蓋所有的邊緣情況。

回答

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' 
0

請檢查以下代碼。總體思路是首先檢查輸入值中是否有點符號。然後,如果條件檢查數字的第一部分(00.或000.或10.)是否除以數字1,然後結果不等於0,則將值分割爲點位置.Via。這將確保整數部分不zero's.After此如果有條件我使用的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>

+0

我們不使用jQuery更多的,特別是如果OP沒有標記他的問題'jQuery'。 – 2017-07-02 18:43:36

0

下面的評論片段有效地說明你想達到的目標;該函數將您給定的值格式化爲所需的格式。

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