Home > OS >  Replace / Mask Alternative N chars in a String in JavaScript
Replace / Mask Alternative N chars in a String in JavaScript

Time:07-12

I want a solution in JavaScript to replace Alternative characters in a string with a " * ".

we have a string with X chars

mask every alternative N chars in the String

I am able to mask every alternative char with "*"

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"

Not sure how to mask the N values

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 (NOO REGEX)

CodePudding user response:

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));

CodePudding user response:

This code should work:

function stars(str, n = 1) {
  const parts = str.split('')
  let num = n
  let printStars = false
    
  return parts.map((letter) => {
    if (num > 0 && !printStars) {
      num -= 1
      return letter
    }

    printStars = true
    num  = 1

    if (num === n) {
      printStars = false
    }

    return '*'
  }).join('')
}

console.log(stars('14124123123'), 1)
console.log(stars('14124123123', 2), 2)
console.log(stars('14124123123', 3), 3)
console.log(stars('14124123123', 5), 5)
console.log(stars(''))

Cheers

CodePudding user response:

This requires you to use the current mask as an argument and build your code upon it.

I also edited the function to allow other characters than the "*"

const number = 'abcdefghijklmnopqrstuvwxyzzz';

for(let mask = 1; mask <= 9; mask  ){
  console.log("Current mask:", mask, " Value: ",applyMask(number, mask));
}


function applyMask(data, mask, defaultMask = '*'){
  // start i with the value of mask as we allow the first "n" characters to appear
  
  let i;
  let str = data;
  for(i = mask; i < data.length ; i =mask*2){
  
    // I used the same substring method you used the diff is that i used the mask to get the next shown values
    //                                                                    HERE
    str = str.substring(0, i)   defaultMask.repeat(mask)   str.substring(i   mask); 
  }
  
  // this is to trim the string if any extra "defaultMask" were found 
  // this is to handle the not full size of the mask input at the end of the string
  return str.slice(0, data.length)
  
}

  • Related