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, '$& '));