How Do I Truncate by Word Instead of Character

How can I make the code look at words instead of characters? Using just characters, the code cuts off whatever word goes passed the character count. I’d rather have the code stop at the last word. Any ideas? Here’s my code:

$w.onReady(function () {
$w(" #dataset1 “).onReady(function () {
const shortTextLength = 115;
let fullText = $w(’ #dataset1 ‘).getCurrentItem().plainContent;
if (!fullText) {
$w(’ #text19 ‘).collapse();
$w(’ #button5 ‘).collapse();
} else {
if (fullText.length <= shortTextLength) {
$w(’ #text19 ‘).text = fullText;
$w(’ #button5 ').collapse();
} else {
let shortText = fullText.substr(0, shortTextLength) + " …”;
$w(’ #text19 ').text = shortText;
}
}
});
});

Thank you so much in advance.

Hey @davidallenfarrell !

You can use the JS method - split() in order to turn a string into an array of strings, by separating the string at each instance of a specified separator string.
If you’d use it with an empty string ( " ") the result would be an array of all the words in the sentence.

Let me know if it works for you!

Doron.

hey david,
adding to what doron said, you can use my truncate function that i have created for you,


function truncateSentence(sentence , limit){
if(sentence.length>limit){
let leftSize = limit;
let finalSentence = '';
let sentenceArr = sentence.split(' ');
for(const word of sentenceArr){
if(word.length>leftSize){
break;
}else{
finalSentence +=' '+word;
leftSize-=word.length;
}
}
finalSentence +='...';
return finalSentence;
}
else{
return sentence;
}
}

tell me if it works for you,
Gal.

I’m sorry. I’m a noob at this, my friend. I can’t get the code to work. I’m not exactly sure what I replace. I replacing everything I have as far back as “function,” but then I get a parsing error for the token, etc.

Not sure what I’m doing.