Posted 5 months ago. Visible to the public.

Automated wordbreaks for long words

The problem:

So I had the issue that User input (coming from many different sources and users) often contains the same long word. Maybe that's a super german thing to have lots of long words I have to deal with. This long word needs to be fully visible on small screens but none of the automated word-break solutions offered by css ( is clever or supported enough to be a good solution. So I had to come up with my own.

The Solution:

I wrote an unpoly compiler that crawls the document and replaces all occurencies of certain word and puts a soft-hyphen (­, or \xAD) where i want the word to break. This is only done in text nodes in order to not break url's in link-tags.

up.compiler('[break-long-words]', (element) => { const wordBreaks = { 'Fahrsicherheitstraining': "Fahr\xADsicherheits\xADtraining", 'Fahrsicherheitszentrum': 'Fahr\xADsicherheits\xADzentrum', 'Kreisverkehrswacht': 'Kreis\xADverkehrswacht', 'Berufsgenossenschaft': 'Berufs\xADgenossenschaft', } const keys = Object.keys(wordBreaks) function textNodes(node){ let textNodes = [] let walk = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, null, false) let nextNode while (nextNode = walk.nextNode()) { textNodes.push(nextNode) } return textNodes } keys.forEach((key) => { let nodes = textNodes(element) nodes.forEach((node) => { node.textContent = node.textContent.replace(new RegExp(key, 'gi'), wordBreaks[key]) }) }) })

This might not be a clever idea on sites with a lot of text, because crawling long texts can get rather expensive and doing it for every long word does not make it better, but in my case the pages are not very content-heavy and there is no remarkable jump during page-build.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Jakob Scholz
Last edit:
4 months ago
by Jakob Scholz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Jakob Scholz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more