Skip to content

Instantly share code, notes, and snippets.

@reecelucas
Last active May 25, 2023 15:21
Show Gist options
  • Save reecelucas/6157bb475161f39fe6427b5e6da0995c to your computer and use it in GitHub Desktop.
Save reecelucas/6157bb475161f39fe6427b5e6da0995c to your computer and use it in GitHub Desktop.
Prevent orphaned word in string
export const preventOrphanWord = (string) => {
const words = string.trim().split(' ');
// Only proceed if we've got at least 3 words
if (words.length < 3) {
return string;
}
const [nextToLastWord, lastWord] = words.slice(-2);
const precedingWords = words.slice(0, words.length - 2);
// Put the array of words back together, joining the last two words with `&nbsp;`
return [...precedingWords, `${nextToLastWord}\u00A0${lastWord}`].join(' ');
};
// Example usage
const string = 'Sint mollit deserunt excepteur elit. Labore est do commodo labore occaecat anim et sunt ut consectetur.';
const stringWithoutOrphan = preventOrphanedWord(string);
console.log(stringWithoutOrphan) // Sint mollit deserunt excepteur elit. Labore est do commodo labore occaecat anim et sunt ut&nbsp;consectetur.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment