用空格jquery替换每第四个输入值后?

时间:2017-02-17 13:50:42

标签: javascript jquery

所以我想要实现的是每隔四分之一被空间取代。 就像我开始在输入1234123412341234上写入按键, 当用户输入时,我想达到1234 1234 1234 1234。

<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之后创建一个空格。 但如何做其余的投入价值呢?提前谢谢。

2 个答案:

答案 0 :(得分:5)

您可以使用替换并查找四个字符。

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

答案 1 :(得分:4)

这可能就是你要找的东西

注意当你快速输入时它有点错误,我修理它atm&lt; - 应该没问题

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