Automated wordbreaks for long words

Posted . Visible to the public.

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 ( https://justmarkup.com/articles/2015-07-31-dealing-with-long-words-in-css/ Show archive.org snapshot ) 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 Show archive.org snapshot 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.

Jakob Scholz
Last edit
Jakob Scholz
License
Source code in this card is licensed under the MIT License.
Posted by Jakob Scholz to makandra dev (2019-11-25 09:44)