How to add Line Break after every 64 chars?

I've a text file to which I want to add line break after every 64 chars. How can I add this using node-red?

does the file already contain line breaks or is it one big string?
do spaces and other special characters count in the 64 characters?

I'd probably use a function node and first get the lenth of the text (using javascript 'length' method) and then have a loop read the text using the javascript 'substring' method to grab 64 characters at a time, add a 'new line' character and stick it into a new string.

Once the loop had processed the input file, I'd exit the loop and write the new string to a new file.

It is one very long string. Actually it is a base64 certificate in 1 line. I have to add the line break after every 64 characters to make the certificate a valid file.

There may be a way to use a regex expression to do it all in one go, but not being a regex expert (it hurts my head) I'd go with the function.

Assuming the string is in msg.payload then the reg ex would be:

msg.payload = msg.payload.replace(/(.{64})/g,'$1\n');
return msg;
1 Like

Awesome! Works like charm! Thanks @knolleary and @zenofmud

See I knew there would be a simple regex way of doing it (but it still hurts my brain :grin:)

2 Likes

Replace also works using a change node and JSONata

$replace(payload, /(.{64})/, '$1\n')

But the magic comes from @knolleary :wink:

1 Like

Good Morning,
I tried to use your magic code to display a string in a text node on the dashboard and I expected to see a several lines of text, each 10 characters long, but it looks like this:
grafik

General question: How can I display "formatted text" (length / line break) on the dashboard.

Thanks
Thomas

PS:
I have read the warning about reviving the old post and hope that it is still ok for you to have replied to it.

<pre>{{msg.payload}}</pre> ?

image