Search code examples
javascriptstringmasking

Masking a string


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?


Solution

  • You could replace each pattern part with the wanted data.

    function format(value, pattern) {
        let i = 0;
        const v = value.toString();
        return pattern.replace(/#/g, _ => v[i++]);
    }
    
    console.log(format(123456789, '## ## ## ###'));