Node Script - Replace Text Using Counter

Posted on Oct 2, 2021 (last modified Aug 27, 2022)

Here's a Node.js script that replaces all instances of a given substring found in a text file with an incrementing number. You can use the node script itself or just steal the technique for use in your own JavaScript code.

This script reads a source text file and replaces all instances of a given substring found in the file with a number that is incremented for each instance of the substring replaced. So, take the following string, for example, and suppose that the substring, 000, is what we wish to replace:

Hello 000 world 000 nodejs 000 is 000 really 000 useful 000!

Given an INCREMENT of 5, the string could become:

Hello 5 world 10 nodejs 15 is 20 really 25 useful 30!

With a PREFIX value of "A_" and suffix value of "_B", it could become:

Hello A_5_B world A_10_B nodejs A_15_B is A_20_B really A_25_B useful A_30_B !

// replaceTextUsingCounter.js const fs = require('fs') const SOURCE_FILE = '../my-app/input.json' const DEST_FILE = '../my-app/output.json' const REPLACE_REGEX = /replace-me/g // This defines, in REGEX, the substring to find. const PREFIX = '' // Value will be prefixed to the counter when substring is replaced; use '' for no prefix const SUFFIX = '' // Value will be appended to the counter when substring is replaced; use '' for no suffix const START_COUNT = 0 // The number to start your counter on const INCREMENT = 5; // How much to increment for each substring found // Read text file for content to perform search and replace operation on... const fileContents = fs.readFileSync(SOURCE_FILE).toString() // Initialize a counter with a given starting count... let counter = START_COUNT; // Call string replace function on the content. // For each instance of the given search substring found, // fire a function that returns what to replace the string segment with... const modifiedContent = fileContents.replace(REPLACE_REGEX, function() { let replacementString = PREFIX + counter + SUFFIX; // the first substring replaced should have starting count counter = counter + INCREMENT; // successive substrings replaced will be incremented return replacementString }); fs.writeFile(DEST_FILE, modifiedContent, function (err) { if (err) { return console.log(err); } console.log('COMPLETE! Check destination file: ' + DEST_FILE); }); To use this script, place it in your project, install the fs dependency with npm install fs --save-dev, update variables in the file as per your need, and then run with node replaceTextUsingCounter.js.