【问题标题】:Save String content into a file with new lines (\n) in JavaScript在 JavaScript 中使用换行符 (\\n) 将字符串内容保存到文件中
【发布时间】:2022-12-02 19:13:34
【问题描述】:

I\'m trying to save some string content into a file from JavaScript. Below is my code and I\'m getting issues because of new lines in the String content.

How to save a file with preserving new lines?

var text = \"Hello \\n World!\"
var file = new Blob([text], {{type:\'text/plain\'}});
var anchor = document.createElement(\"a\");
anchor.href = URL.createObjectURL(file);
anchor.download = \"file.log\";
anchor.click();
            

I\'m getting below error in my browser,

  • How do you load this code?
  • The error you\'ve shown in the screenshot makes it look like the \\n you\'ve shown in your code isn\'t really a \\n (an escape sequence, backslash followed by n which produces a newline in the resulting string), but an actual newline in the string literal, which is indeed a syntax error. But it\'s really not clear how you\'re getting from A (the code you\'ve posted) to B (the error in the screenshot). Could you clarify?
  • Note that in any case, the double curly braces in var file = new Blob([text], {{type:\'text/plain\'}}); are an error, it should be just var file = new Blob([text], {type:\'text/plain\'});.

标签: javascript file


【解决方案1】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 2016-03-20
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多