0

I have a code that replaces in a file all line breaks and sustitute for comma.

var fs = require('fs');

var str = fs.readFile('output.txt', 'utf-8', function(err, data) {
    if (err) throw err;
    console.log(data.replace(/\r\n/g, ','));
});

I'm trying to make a version that every 3 executions add a line break.

How I can accomplish this?

Monikhe
  • 35
  • 3

2 Answers2

0
data.replace(/\n/g, ",").replace(/(([^,]*,){2}[^,]*),/g, '$1\n')

Or

data.replace(/\r\n/g, ",").replace(/(([^,]*,){2}[^,]*),/g, '$1\r\n')
4b0
  • 21,981
  • 30
  • 95
  • 142
Newbee
  • 23
  • 3
0

String.prototype.replace can accept a replacer function as second argument, docs here. Using a function fits your case perfectly.

You can create a function that keeps an execution counter in its closure, then conditionally yields a line break on every 3 replacements.

function ReplacerFactory() {
  var execCount = 0;

  function replacer() {
    execCount++;
    if (execCount % 3) return ',';
    return '\n';
  }

  return replacer;
}

console.log(data.replace(/\r\n/g, ReplacerFactory()));

var data = `a
quick
brown
fox
jumps
over
a
lazy
dog
yo!
`;

function ReplacerFactory() {
  var execCount = 0;

  function replacer() {
    execCount++;
    if (execCount % 3) return ',';
    return '\n';
  }

  return replacer;
}

console.log(data.replace(/\n/g, ReplacerFactory()));
hackape
  • 18,643
  • 2
  • 29
  • 57