Masking a string
You could replace each pattern part with the wanted data.
function format(value, pattern) { var i = 0, v = value.toString(); return pattern.replace(/#/g, _ => v[i++]);}console.log(format(123456789, '## ## ## ###'));
I needed one that masks any character with a "*", from the beginning or end of the string, so I wrote the following:
"use strict";module.exports = { /** * @param {string} str * @param {string} maskChar * @param {number} unmaskedLength * @param {boolean} [maskFromStart] * @returns {string} */ mask(str, maskChar, unmaskedLength, maskFromStart = true) { const maskStart = maskFromStart ? 0 : Math.max(0, unmaskedLength); const maskEnd = maskFromStart ? Math.max(0, str.length - unmaskedLength) : str.length; return str .split("") .map((char, index) => { if (index >= maskStart && index < maskEnd) { return maskChar; } else { return char; } }) .join(""); },};