Skip to content
Picture of Alex Carpenter

· views

Preventing widows with a widont helper function

Words that break to their own line when there is not enough horizontal space are often refered to as "widows". This can be awkward, so it's often common to ensure there are always at least two words on the last line.

Getting started with

To prevent this from happening, it's common to add a   in between the last two words. Here is a helper function that uses Regex to find the last word with a space before it in a string, and replaces the space with a  .

const widont = (str) => {
const REGEX = /\s((?=(([^\s<>]|<[^>]*>)+))\2)\s*$/;
return str.replace(REGEX, '\u00A0$1');

Now in the case that JavaScript breaks to its own line, both with and JavaScript will go to the next line. Preventing any awkward "widows" across your website.

Getting started
with JavaScript