随便输入多个字符,就会发现四个数字自动加空格的 function test(){ var len=document.getElementById('card').value.length; var reg = /\s{1,}/g; var card_ = ""; var card=document.getElementById('card').value; //去除空格 card = card.replace(reg,""); for(var i = 0;i < len;i++){ if(i == 3||i == 7 ||i == 11||i == 15) { card_ = card_ + card.charAt(i) + " "; } else { card_ = card_ + card.charAt(i); } } document.getElementById("card").value = card_; } [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]