Skip to content

Instantly share code, notes, and snippets.

@eclarrrk
Created December 21, 2021 14:50
Show Gist options
  • Save eclarrrk/9350baabeb2d0173670acc30659d9001 to your computer and use it in GitHub Desktop.
Save eclarrrk/9350baabeb2d0173670acc30659d9001 to your computer and use it in GitHub Desktop.
Script that removes the space between the last two words in an element, preventing a hanging widow on the last line
// Add non-breaking space between the last 2 words of the elements selected
var noSpace = document.querySelectorAll(":is(h1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6, *:not(.keep-space)");
for (var i = 0; i < noSpace.length; i++) {
var headline = noSpace[i].innerHTML;
// count the amount of spaces in the headline
var wordCount = headline.split(" ").length;
// if there are 3 spaces or more in the headline...
if (wordCount > 2) {
headline = headline.replace(/ (?=[^ ]*$)/i, "&nbsp;");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment