You can do something like this:
http://jsfiddle.net/ffwAA/4/
What applies this function to a string to obtain the desired formatting:
function formatCode(str){ var result = str; str = str.replace(/\D+/g, ""); var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/); if(m){ result = m[1] + " "; if(m[2]) result += m[2] + " "; if(m[3]) result += m[3] + " "; if(m[4]){ result += m[4].split(/(\d{4})/).join(" "); result = result.replace(/\s+/g, " "); } } return result; }
And using this jQuery to configure it:
function update(obj){ var val = obj.value; var got = formatCode(val); if(got != val) obj.value = got; } var timer; var prev_val = ""; $('#code').keyup(function(){ clearTimeout(timer);
source share