Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Reemplazar / enmascarar N caracteres alternativos en una cadena

Quiero reemplazar algunos caracteres en una cadena con un "*", de la siguiente manera:

Dado N, deje los primeros N caracteres como están, pero enmascare los siguientes N caracteres con "*", luego deje los siguientes N caracteres sin cambios, etc., alternando cada N caracteres en la cadena.

Puedo enmascarar cada carácter alterno con "*" (el caso donde N es 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)

Producción:

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

Pero no sé cómo realizar la máscara con diferentes valores para N.

Ejemplo:

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

¿Cuál es la mejor manera de lograr esto sin expresiones regulares?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puede usar Array.from para asignar cada carácter a "*" o al carácter sin cambios, según el índice. Si la división entera del índice por n es impar, debe ser "*". Finalmente, vuelva a convertir esa matriz en una cadena con 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));

about 4 years ago · Juan Pablo Isaza Report

0

Este código debería funcionar:

 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(''))

Salud

about 4 years ago · Juan Pablo Isaza Report

0

Esto requiere que use la máscara actual como argumento y construya su código sobre ella.

También edité la función para permitir otros caracteres además del "*"

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!