【问题标题】:JavaScript delete text in every 3rd line in a txt documentJavaScript 删除 txt 文档中每 3 行的文本
【发布时间】:2019-02-15 04:39:56
【问题描述】:

我需要一些帮助来自动执行一项任务。

Before.txt

01 ABCDE
02 ABCDE
03 ABCDE
04 ABCDE
05 ABCDE
06 ABCDE
07 ABCDE
08 ABCDE
09 ABCDE

After.txt
01 ABCDE
02 ABCDE
03
04 ABCDE
05 ABCDE
06
07 ABCDE
08 ABCDE
09

【问题讨论】:

  • 那么你尝试了什么?
  • 嗨!请使用tour(您将获得徽章!)并通读help center,尤其是How do I ask a good question? 您最好的选择是进行研究,search 以获取有关 SO 的相关主题,然后试一试. 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。
  • 想出一个想法比立即发布问题要容易得多。基本概念:逐行读取文件。每三次迭代只接受初始字符(使用计数器等)。

标签: javascript node.js text


【解决方案1】:

只需将words 替换为您的字符串即可。 result 是最后一个字符串,它的所有值由一个新行连接在一起。

var words = "01 ABCDE\n02 ABCDE\n03 ABCDE\n04 ABCDE\n05 ABCDE\n06 ABCDE\n07 ABCDE\n08 ABCDE\n09 ABCDE";

// we split the file into an array using the new lines as the split point
var lines = words.split(/\r?\n/);

for (var i = 0; i < lines.length; i++) {
  // we take every third line and delete all the chars from 3 and beyond
  if (i > 0 && i % 3 === 0)
    lines[i] = lines[i].substring(0, 2);
}
// we join the values again
result = lines.join('\n')

【讨论】:

    猜你喜欢
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多