[英]Replace a line in txt file using JavaScript
我正在嘗試使用 JavaScript 簡單地替換文本文件中的一行。
這個想法是:
var oldLine = 'This is the old line';
var newLine = 'This new line replaces the old line';
現在我想指定一個文件,找到oldLine
並將其替換為newLine
並保存。
誰能在這里幫助我?
只是建立在 Shyam Tayal 的回答之上,如果您想替換與您的字符串匹配的整行,而不僅僅是一個完全匹配的字符串,請執行以下操作:
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);
});
});
'm' 標志會將 ^ 和 $ 元字符視為每行的開頭和結尾,而不是整個字符串的開頭或結尾。
所以上面的代碼會轉換這個txt文件:
one line
a line to replace by something
third line
進入這個:
one line
a completely different line!
third line
這應該做
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);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.