The following RegEx formats given string to following output block pattern:
123 456 78 90 (= 3 digits 3 digits 2 digits 2 digits )
RegEx:
anubhava's and Wiktor's solutions are clever, but I don't think I'd use a regular expression to do it; the solutions feel too complex to maintain. (This is a judgement call.) Here's an approach that gets the individual digits and inserts spaces after the third digit and after every subsequent digit whose index position is an odd number:
result = [...str].map((d, i) => d + (i === 2 || (i >= 5 && i % 2 === 1) ? " " : "")).join("");
Live Example:
const tests = [
["1234", "123 4"],
["1234567", "123 456 7"],
["123456789", "123 456 78 9"],
["1234567890123", "123 456 78 90 12 3"],
];
function format(str) {
return [...str].map((d, i) => d + (i === 2 || (i >= 5 && i % 2 === 1) ? " " : "")).join("");
}
for (const [str, expected] of tests) {
const result = format(str);
console.log(`|${str}|`, "=>", `|${result}|`, result === expected ? "OK" : "*** ERROR");
}
Here's a version that works in ES5-only environments:
result = str.split("").map(function(d, i) {
return d + (i === 2 || (i >= 5 && i % 2 === 1) ? " " : "");
}).join("");