val = "123456"; val = val.replace(/.+?(?=\D|$)/, function(x) { return x.replace(/(\d)(?=(?:\d\d\d)+$)/g, "$1 "); }); alert(val);