2017-02-17 75 views
3

所以我想實現的是每隔四分之後用空格替換。 就像我開始寫在按鍵上輸入1234123412341234, 我想實現1234 1234 1234 1234,當用戶鍵入時。用空格jquery替換每個第四個輸入值之後?

<input type="text" id="number" maxlength=19 /> 

這裏是JS

$('#number').on('keypress', function() { 
    if (this.value.length >= 4) { 
    this.value = this.value.slice(0, 4) + ' '+this.value.slice(5, 9); 
    } 

所以這個代碼僅創建第四後一個空間,1234 123412341234. 但如何對輸入值的其餘部分嗎?提前致謝。

+0

jQuery是不是該解決方案在這裏,你可以用標準的JS做到這一點 - http://stackoverflow.com/questions/32030727/replace-every-nth-character-from- a-string – G0dsquad

回答

4

這可能是你正在尋找

注意它的錯誤,當你鍵入快一點什麼,我是個大氣壓修復它< - 應該罰款

$(function(){ 
 
    $("input").keydown(function(){ 
 
     if ((($(this).val().length+1) % 5)==0){ 
 
      $(this).val($(this).val() + " "); 
 
     } 
 
    });   
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input />

+0

So so tnx :) – NemanjaD

+0

歡迎您:) –

5

您可以使用替換並查找四個字符。

console.log('1234123412341234'.replace(/.{4}/g, '$& '));

+0

偉大的解決方案。 –

+0

打字時無法正常工作。 – Mohammad

相關問題