'123321'.replace(/(\d)(?=(\d{3})+$)/g, '$1 ');
'123321'.replace(/\d{4}(?=.)/g, '$& ');
let num = 3; let regexp = new RegExp(`(\\d)(?=(\\d{${num}})+$)`, `g`); alert('123321'.replace(regexp, '$1 ')); let k = 4; let reg = new RegExp(`\\d{${k}}(?=.)`, `g`); alert('123321'.replace(reg, '$& '));