【问题标题】:Remove string from txt file从 txt 文件中删除字符串
【发布时间】:2018-10-18 15:15:04
【问题描述】:

所以基本上我想从 txt 文件中删除字符串。

使用 fs

输入示例:

string1
string2
string3
string4

删除string3

删除后会是这样的:

string1
string2
string4

【问题讨论】:

  • 您应该可以使用FS打开文件,找到并删除示例字符串,然后再次使用FS保存文件。
  • 对不起,你能给我举个例子吗?
  • 有一个名为 FileSystem 的 Node 模块(它带有 Node 安装)。如果你需要const fs = require("fs"),你应该用 fs.openFileSync(//put params in here) 打开文件,读取内容,编辑,然后用 fs.WriteFile() 保存。
  • 这里是文件系统模块的文档:nodejs.org/api/fs.html

标签: javascript node.js fs


【解决方案1】:

读取文本文件获取变量中的内容然后使用String.replace

例如

var stringContent="Here goes the content of the textFile after read"
 var res=stringContent.replace('string3','');
//write back res to the file or do what ever

【讨论】:

    【解决方案2】:

    正如 brk 回答的那样,字符串上的 replace 方法可以完成这项工作。

    另一种方法是 var a = new Array(); a = string.split("searching_string"); string = a.join(""); 认为它应该工作。但是,当replace 存在时,为什么要让它变得复杂呢?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多