Last active
May 25, 2023 15:21
-
-
Save reecelucas/6157bb475161f39fe6427b5e6da0995c to your computer and use it in GitHub Desktop.
Prevent orphaned word in string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ` ` | |
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 consectetur. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment