Chat messages, SMS gateways, cell values and API fields all have a character limit, and a nightly summary will eventually blow past it. splitTextUnderLimit(text, limit) splits a long message into chunks that are each at most limit characters, breaking at line breaks first, then spaces, and only cutting mid-word when a single word is longer than the limit.
When to use
- Posting long summaries to Google Chat or Slack webhooks
- Writing text into cells (the per-cell limit is 50,000 characters)
- Any API field with a hard maximum length
How to use this snippet
/**
* Split text into chunks of at most `limit` characters.
* Prefers line breaks, then spaces; only hard-cuts words longer than the limit.
*
* @param {string} text
* @param {number} limit max characters per chunk (e.g. 4000)
* @return {string[]}
*/
function splitTextUnderLimit(text, limit) {
text = String(text == null ? '' : text);
if (!limit || limit < 1) throw new Error('splitTextUnderLimit: limit must be >= 1');
var chunks = [];
var rest = text;
while (rest.length > limit) {
var window = rest.slice(0, limit + 1);
var cut = window.lastIndexOf('\n');
if (cut <= 0) cut = window.lastIndexOf(' ');
if (cut <= 0) cut = limit; // one very long word: hard cut
chunks.push(rest.slice(0, cut).replace(/\s+$/, ''));
rest = rest.slice(cut).replace(/^[\n ]+/, '');
}
if (rest.length || !chunks.length) chunks.push(rest);
return chunks;
}
Example
function postLongSummary(summaryText) {
var url = PropertiesService.getScriptProperties().getProperty('CHAT_WEBHOOK_URL');
var parts = splitTextUnderLimit(summaryText, 4000);
parts.forEach(function (part, i) {
var label = parts.length > 1 ? '(' + (i + 1) + '/' + parts.length + ')\n' : '';
postToChatWebhook(url, label + part);
});
}
Tips:
- Leave room for any label you add: if you prefix “(2/3)\n”, split at
limit - 10. - Check your destination's real limit and stay a little under it. Limits are sometimes counted in bytes rather than characters, which matters for emoji and accented text.
- Pairs with postToChatWebhook for chat summaries.
Tip: NitroGAS Co-Pilot can wrap an existing “post summary” function so long messages are split automatically. Paste the function.
Happy Coding!
