Home > Software design >  Replace word and count the total number of replace word in nodejs
Replace word and count the total number of replace word in nodejs

Time:06-12

I am trying to replace word from a file with counting the total number of replaced word.how can I do it . This was my approach:

var fs = require('fs')
var counter = 0;
fs.readFile('test.txt', 'utf8', function (err,data) {

  var formatted = data.replace(/old line/g, 'This new line ',function(a){
    counter  ;
  
 })

console.log(counter   'Numbers of word Replaced')

 fs.writeFile('test.txt', formatted, 'utf8', function (err) {
    if (err) return console.log(err);
 });
});

CodePudding user response:

First, you should use the String#replaceAll function to replace all occurrences of the matched string.

The function accepts only two arguments:

  • The first being either a String or a RegEx
  • The second being either a String or a replacer Function

Here is how your approach should be updated (avoiding var keyword):

const fs = require('fs')
let counter = 0;
fs.readFile('test.txt', 'utf8', function (err, data) {
  const formatted = data.replace(/old line/g, function(a) {
    counter  ;
    return 'This new line ';
 });

 console.log(counter   'Numbers of word Replaced')

 fs.writeFile('test.txt', formatted, 'utf8', function (err) {
    if (err) return console.log(err);
 });
});
  • Related