Home > Mobile >  Save String content into a file with new lines (\n) in JavaScript
Save String content into a file with new lines (\n) in JavaScript

Time:12-02

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();
            

Note: I'm using python code as below to execute above JS code.

log_lines : str = "Hello \n World"

q.page['meta'].script = ui.inline_script(
            f'''
            var file = new Blob(["{log_lines}"], {{type:'text/plain'}});
            var anchor = document.createElement("a");
            anchor.href = URL.createObjectURL(file);
            anchor.download = "test.log";
            anchor.click();
            '''
        )

Python SDK: enter image description here enter image description here

CodePudding user response:

I fixed this with below code, Needed to replace \n with \\n

log_lines : str = "Hello \n World".replace("\n", "\\n")

q.page['meta'].script = ui.inline_script(
            f'''
            var file = new Blob(["{log_lines}"], {{type:'text/plain'}});
            var anchor = document.createElement("a");
            anchor.href = URL.createObjectURL(file);
            anchor.download = "test.log";
            anchor.click();
            '''
        )

CodePudding user response:

To preserve the new lines in your string when saving it to a file, you can use the encodeURIComponent function to encode the string before creating the Blob object. This will ensure that any special characters, such as new lines, are properly encoded in the file. Here's an example:

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

When you open the downloaded file, you should see the string with the new line character preserved.

  • Related