Search code examples
javascriptstringreplacemaskmasking

Replace / mask alternative N chars in a string


I want to replace some characters in a string with a "*", in the following way:

Given N, leave the first N characters as-is, but mask the next N characters with "*", then leave the next N characters unchanged, ...etc, alternating every N characters in the string.

I am able to mask every alternating character with "*" (the case where N is 1):

let str = "abcdefghijklmnopqrstuvwxyz"
for (let i =0; i<str.length; i +=2){ 
    str = str.substring(0, i) + '*' + str.substring(i + 1); 
}
console.log(str)

Output:

"*b*d*f*h*j*l*n*p*r*t*v*x*z"

But I don't know how to perform the mask with different values for N.

Example:

let string = "9876543210"

N = 1; Output: 9*7*5*3*1*
N = 2; Output: 98**54**10
N = 3; Output: 987***321*

What is the best way to achieve this without regular expressions?


Solution

  • You could use Array.from to map each character to either "*" or the unchanged character, depending on the index. If the integer division of the index by n is odd, it should be "*". Finally turn that array back to string with join:

    function mask(s, n) {
        return Array.from(s, (ch, i) => Math.floor(i / n) % 2 ? "*" : ch).join("");
    }
    
    let string = "9876543210";
    console.log(mask(string, 1));
    console.log(mask(string, 2));
    console.log(mask(string, 3));