Last active
August 19, 2020 13:02
-
-
Save jpescada/3ba56eb38be7a59dc8c829b6d80b23c0 to your computer and use it in GitHub Desktop.
Prevent text widows
This file contains hidden or 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
| // Replaces a set number of spaces in text with non-breaking spaces to prevent widows | |
| // Example use in React: <div dangerouslySetInnerHTML={{ __html: preventWidows(text) }} /> | |
| export function preventWidows(text: string, spaces: number = 3): string { | |
| const regx: RegExp = /\s/g | |
| const spacesCount: number = (text.match(regx) || []).length | |
| const spacesTarget = spacesCount - spaces | |
| let i: number = 0 | |
| text = text.replace(regx, match => { | |
| i++ | |
| return i > spacesTarget ? ' ' : match | |
| }) | |
| return text | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment