Skip to content

Instantly share code, notes, and snippets.

@jpescada
Last active August 19, 2020 13:02
Show Gist options
  • Select an option

  • Save jpescada/3ba56eb38be7a59dc8c829b6d80b23c0 to your computer and use it in GitHub Desktop.

Select an option

Save jpescada/3ba56eb38be7a59dc8c829b6d80b23c0 to your computer and use it in GitHub Desktop.
Prevent text widows
// 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 ? '&nbsp;' : match
})
return text
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment