0

I am using substring to trim my text:

const trimmedLead = lead.substring(0, 118) + '...'

But now it's also breaking words. How do you achieve the same in Javascript, but without breaking words?

meez
  • 3,783
  • 5
  • 37
  • 91

2 Answers2

0

Get the substring, then get the substring of that substring up until the last space, then add the ...:

const lead = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'

const trimmedLead = lead.substring(0, 118)
                        .substring(0, lead.substring(0, 118).lastIndexOf(' ')) +
                        '...'
console.log({ trimmedLead, length: trimmedLead.length});
dave
  • 62,300
  • 5
  • 72
  • 93
0

You can split the string where you prefer, then you can check if part one ends with a character AND if part two starts with a character. If both of those are true, you split a word. If you split a word, use replace to cut back to the end of a word's boundary.

function trimDownToWord(string, maxLength) {
  if (string <= maxLength) {
    return string;
  }

  let first = string.substr(0, maxLength);
  const second = string.substr(maxLength);

  if (/\w$/.test(first) && /^\w/.test(second)) {
    first = first.replace(/\b[^\w]*\w+$/, '');
  }

  return first.trim() + '...';
}



const lead = `This is multiple words, many fun words to read!`

// Without word trimming:
const trimmedAtLength = lead.substring(0, 25) + '...';
console.log(trimmedAtLength);

// With word trimming:
const trimmedByWords = trimDownToWord(lead, 26);
console.log(trimmedByWords);
KevBot
  • 17,900
  • 5
  • 50
  • 68