I am trying to simply replace a line in a text file using JavaScript.
The idea is:
var oldLine = 'This is the old line';
var newLine = 'This new line replaces the old line';
Now i want to specify a file, find the oldLine
and replace it with the newLine
and save it.
Anyone who can help me here?
We can: 1) open up a text file; 2) read the text into a variable; 3) do a search-and-replace on that variable; and 4) re-save the text file. We can even do all that from the command line, although we’ll hold off on that for a moment.
From the command line, how can I use a script to open a file and replace text; for example, how can I replace all instances of “Jim” with “James”? Hey, JW. As we’ve found out numerous times when dealing with text files, there is no obvious way to do this; that is, there is no ReplaceText command that can open a text file and find and replace text.
The replace () is an in-built method provided by JavaScript which takes the two input parameters and returns a new String in which all or first matches of a pattern are replaced with a replacement. The first input parameter is a pattern which is usually a string or RegExp.
We are using the String.replace() method of regex to replace the new line with <br>. The String.replace() is an inbuilt method in JavaScript that is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged.
Just building on Shyam Tayal's answer, if you want to replace an entire line matching your string, and not just an exact matching string do the following instead:
fs.readFile(someFile, 'utf8', function(err, data) {
let searchString = 'to replace';
let re = new RegExp('^.*' + searchString + '.*$', 'gm');
let formatted = data.replace(re, 'a completely different line!');
fs.writeFile(someFile, formatted, 'utf8', function(err) {
if (err) return console.log(err);
});
});
The 'm' flag will treat the ^ and $ meta characters as the beginning and end of each line, not the beginning or end of the whole string.
So the above code would transform this txt file:
one line
a line to replace by something
third line
into this:
one line
a completely different line!
third line
This should do it
var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {
var formatted = data.replace(/This is the old line/g, 'This new line replaces the old line');
fs.writeFile(someFile, formatted, 'utf8', function (err) {
if (err) return console.log(err);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With