Any ways to return the last X characters of a string?

Hey, long time lurker, first time poster so be kind ^_^. Really enjoying playing more and more with n8n. I am working on a process where I am building out a chatbot with AI.

The string will increase over the conversation with the questions and answers being included and we are capped by the limits of prompt, what I want to be able to do is to measure the number of characters (I have found a useful post with that solution!) and if over a certain number then return the string with say the last 1500 characters only so it will exclude the characters at the start of the string.

Is there any way to do this with n8n? Any tips or assistance to point me in the right direction would be much appreciated!

I ended up plugging in some of the javascript snippets from the documentation into a codex model with commands and then asked the AI to solve this problem for me. It gave me this output;

const text = items[0].json.text;
const last1500Chars = text.substring(text.length - 1500);
items[0].json.last_1500_chars = last1500Chars;
return items;

Tested it and it seems to work so looks like I solved my own problem now :D! What a world we live in.

Hey @stuart,

Welcome to the community :partying_face:

You could also give .slice(-1500) a go which should do the same thing.

String Slice: String.prototype.slice() - JavaScript | MDN

2 Likes

awesome. That saves the need for a function!