Search code examples
javascripthtmlcssword-breakcss-hyphens

Line break a word onto a full line if it contains a hyphen


I am attempting to use javascript so when my h1 element gets to the end of a line if it contains a hyphened word it line breaks the whole word onto the next line so it stops the below.

Issue below

Issue at hand

i want the result to be

Product T Hydra 2000
e-Ticket

This is the javascript I have so far which pushes it onto the next line but this happens for every hyphened word regardless of where it sits within the h1.

let infoBox = document.querySelector('.viewer__info-box');
let h1Element = document.querySelector('.viewer__h1');


let words = h1Element.innerText.split(' ');
for (var i = 0; i < words.length; i++) {
  if (words[i].includes('-')) {
    words[i] = '<br>' + words[i];
  }
}
console.log(words.join(' '));
h1Element.innerHTML = words.join(' ');

I've tried using below to check the width of the div against the content but had no luck.

if (h1Element.scrollWidth <= h1Element.clientWidth) {

has anyone got any ideas on this?


Solution

  • Just replace any standard hyphens with non-breaking hyphens.

    document.querySelectorAll('h1').forEach(h1 => {
      h1.innerHTML = h1.innerHTML.replace('-','\u2011')
    })
    <h1>Product T Hydra 2000 e-Ticket</h1>