Skip to content

Instantly share code, notes, and snippets.

@glenux
Last active January 23, 2021 17:29
Show Gist options
  • Save glenux/ad5e05c1f41cee639fc52ef783b558c2 to your computer and use it in GitHub Desktop.
Save glenux/ad5e05c1f41cee639fc52ef783b558c2 to your computer and use it in GitHub Desktop.
n8n.io Function - Smart text truncate for tweets
let MAX_TWEET_LENGTH = 270;
function naiveCut(str, maxLen){
// Guard
if (str.length <= maxLen) {
return str;
}
return str.slice(0, maxLen-1);
}
function smartCut(str, maxLen, minAmount) {
// Guard
if (str.length <= maxLen) {
return str;
}
let strBackup = str;
let amount;
while(str.length > maxLen) {
// remove last word
str = str.replace(/ [^ ]+$/,'');
// remove trailing whitespace
str = str.replace(/ +$/,'')
amount = str.length / maxLen;
}
if (amount > minAmount) {
return str;
}
return strBackup
}
for (item of items) {
tweet = item.json.contentSnippet;
newTweet = naiveCut(smartCut(tweet, MAX_TWEET_LENGTH, 0.7), MAX_TWEET_LENGTH);
// add ellipsis if needed
if (newTweet != tweet) {
tweet = tweet + " [...]";
}
item.json.contentSnippet = tweet;
}
return items;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment