<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>test</title> <script type="text/javascript"> window.onload =function() { document.getElementById("test").onkeyup =function() { this.value =this.value.replace(/\s/g,'').replace(/(\d{4})(?=\d)/g,"$1 ");; }; }; </script> </head> <body> <input type="text" id="test"/> </body> </html>