Masking a string

Pedro Pam picture Pedro Pam · Jul 11, 2017 · Viewed 15k times · Source

I need to put a received string in this format:

"## ## ## ###" in typescript/javascript

Eg:

"12 34 56 789"

I know there's string-mask and some way via JQuery, is there a simplier way to do it?

Answer

Nina Scholz picture Nina Scholz · Jul 11, 2017

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