Prevent The Last Word In A Title From Wrapping By Itself
Update: CSS to the Rescue!
In 2023 both Chrome and Firefox shipped the
text-wrap: balance
property, which solves this problem without any non-breaking space hacks. Safari has it in Technology Preview, so all browsers will support it soon.This feature is a great example of progressive enhancement, as well. Nobody’s site will break if it’s not supported, they’ll just see slightly less elegant typography.
This is a handy utility function to insert a non-breaking space between the final two words in a string. I got in the habit of doing this in WordPress with a title filter and wanted to have the same feature available when building Javascript sites.
I’m sure someone more clever than myself could manage this with a regex, but this works for me.
function smartTitleWrap(title) {
const words = title.split(" ");
if (words.length <= 4) {
return title;
}
return words.reduce((string, word, index, array) => {
if (0 === index) {
return word;
} else if (array.length - 1 === index) {
return string + String.fromCharCode(160) + word;
} else {
return string + " " + word;
}
}, "");
}