Search code examples
node.jsregexsanitization

Sanitize stream from stdin using node.js


I have this script:

let stdin = '';

process.stdin
  .setEncoding('utf8')
  .resume()
  .on('data', d => {

   stdin+= d;
});


const regexs = [
  [/(?=.*[^a-zA-Z])[0-9a-zA-Z]{7,300}/g, function replacer(match, p1, p2, p3, offset, string) {
    return match.slice(0,2) + 'xxxxx' + match.slice(6);
  }]
];


process.stdin.once('end', end => {

  for(let r of regexs){
    stdin = stdin.replace(r[0], r[1]);
  }
  console.log(stdin);
});

and I am using it like so:

 echo "ageoageag ageagoie ag77eage" | node sanitize-stdin.js 

and I get this:

agxxxxxeag agxxxxxie agxxxxxge

but I really am only looking to replace a string of length 6-300 if it has numbers in it. So the output I am looking for is:

ageoageag ageagoie agxxxxxge

anyone know how to replace the string only if it has at least one number in there?


Solution

  • If your script is modified, how about this modification?

    In your script, match in the function of replacer() is the splitted string. When "ageoageag ageagoie ag77eage" is inputted, each value of ageoageag, ageagoie and ag77eage is given as match. replacer() returns all cased of match as match.slice(0,2) + 'xxxxx' + match.slice(6). By this, agxxxxxeag agxxxxxie agxxxxxge is returned.

    In order to process only match including the number, how about this modification? Please modify the function of replacer() as follows.

    From:

    return match.slice(0,2) + 'xxxxx' + match.slice(6);
    

    To:

    return /[0-9]/.test(match) ? match.slice(0,2) + 'xxxxx' + match.slice(6) : match;
    

    Result:

    ageoageag ageagoie agxxxxxge
    

    If I misunderstood your question and this was not the result you want, I apologize.

    Edit:

    If the values inputted are separated by a space like ageoageag ageagoie ag77eage, how about this modification? In this modification, const regexs is not used.

    From:

    for(let r of regexs){
      stdin = stdin.replace(r[0], r[1]);
    }
    

    To:

    stdin = stdin.split(" ").map(function(e) {
      return e.length > 6 && e.length <= 300 && /[0-9]/.test(e) ? e.slice(0,2) + 'xxxxx' + e.slice(6) : e;
    }).join(" ");