Adding line break at the end of an array not working

Hi,

Here’s my code:

{
  "Name": "Array to txt",
  "CreationDate": "2024-4-13",
  "Commands": [
    {
      "Command": "executeScript",
      "Target": "var linkArray = [\"Saab\", \"Volvo\", \"BMW\"];\n\nvar dataStr =\n\t'data:text/json;charset=utf-8,' +\n\tlinkArray.join('\\n') + '\\n';\n\nvar dlAnchorElem = document.createElement('a');\ndlAnchorElem.setAttribute('href', dataStr);\ndlAnchorElem.setAttribute('download', 'array.txt');\ndlAnchorElem.click();\n",
      "Value": "",
      "Description": ""
    }
  ]
}

I’ve been struggling to add an empty line at the end of the exported txt file that should contain my array items, \n or \r doesn’t seem to be doing anything on its own which is strange, but if you try for example:
\naaaa then a new line will be added just fine with “aaaa” on it
is this a bug or am I missing something?
more important, is there a way I can have my items listed with an empty line at the end?
like this:

A
B
C

can anyone provide some help please?

can anyone provide some help please?

No Offense but… You’re in a UI.Vision forum, and you’re pretty much doing stuff outside of UI.Vision at this point. I think you will get much better support in StackOverflow.

I may have an answer for your question though.
Disclaimer: I’m also a fellow user like you, not a developer of some kind.

Background:
By the way, this is a general JavaScript problem and it’s also appear to be quite a hack. Thanks for the idea, though, I wasn’t even aware you could do this.

The problem you have is because you are setting to a href that implicitly encodes dataStr into an a complete URI which by default trims all trailing whitespaces. Unfortunately “\r” and “\n” are all whitespaces so they are removed at this point:

dlAnchorElem.setAttribute('href', dataStr);

You can check your dlAnchorElem.href value and you will never see that last “\n” symbol you added earlier.

Now, with that being said,

How about using encodeURIComponent()?

var linkArray = ["Saab", "Volvo", "BMW"];

var dataStr =
	'data:text/json;charset=utf-8,' +
	encodeURIComponent(linkArray.join('\n') + '\n');

var dlAnchorElem = document.createElement('a');
dlAnchorElem.setAttribute('href', dataStr);
dlAnchorElem.setAttribute('download', 'array.txt');
dlAnchorElem.click();

You can also sneak that “encodeURIComponent” on the whole dataStr like setAttribute('href',encodeURIComponent(dataStr)) instead of the one I showed earlier.

1 Like