[英]Remove one line in txt file ( NODE.js)
I make a text file "foo\\nbar\\nbas" 我制作一个文本文件“ foo \\ nbar \\ nbas”
When i append coke(with adding \\n), then the file will be "foo\\nbar\\nbas\\ncoke" 当我追加可乐(添加\\ n)时,文件将为“ foo \\ nbar \\ nbas \\ ncoke”
I want to remove the foo. 我要删除foo。
Help me! 帮我!
Fo your use case that you have provided, a simple answer is split on \\n, remove the first item, add the new item to the end, and join the array to form your new string. 对于您提供的用例,一个简单的答案位于\\ n上,删除第一个项目,将新项目添加到末尾,然后加入数组以形成新字符串。
var parts = "foo\nbar\nbas".split("\n").slice(1);
parts.push("coke");
var updated = parts.join("\n");
Other option is to use indexOf to find the first occurrence of \\n
and substring to select the portion of the string, then it is a simple concatenation. 另一个选择是使用indexOf查找
\\n
的第一个匹配项,并使用子字符串选择字符串的一部分,然后进行简单的串联。
var str = "foo\nbar\nbas";
var position = str.indexOf("\n")+1;
var updated = str.substring(position) + "\ncoke";
You can use simple string manipulation if your task is not complicated by further constraints. 如果您的任务不受其他约束的限制,则可以使用简单的字符串操作。 Such is as follows:
如下所示:
var fileContents = "foo\nbar\nbas";
// Read Text File, in this case, I have set it.
fileContents = fileContents.replace("foo\n", "");
fileContents += "\ncoke";
// Write back to file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.