Search code examples
javascripthtmlcssword-wrap

word-wrap: break word; fix or alternative


With word-wrap: break-word; if the word is going to break anyway, I dont want a line-break first, it is useless and ugly. How to avoid that?

Example:

Given a div with word-wrap: break-word; and a width equivalent to those 23 "x" characters like so:

xxxxxxxxxxxxxxxxxxxxxxx


The div innerHTML is "xx xxxxxxxxxxxxxxxxxxxxxxxxxxxx" like so:

<div>xx xxxxxxxxxxxxxxxxxxxxxxxxxxxx</div>   


This is how the innerHTML of the div is displayed vs how it is wanted respecting the 23 "x" width.

What happens:
xx
xxxxxxxxxxxxxxxxxxxxxxx
xxxxx

What I want:
xx xxxxxxxxxxxxxxxxxxxxx
xxxxxxxx



word-break: break-all; and similar or more recent attributes are not a solution to the problem. I dont want words that can avoid breaking to break. I only want words with a width superior than the container width to break BUT without line-break first like with word-wrap: break-word; because it is simply useless and ugly.


Solution

  • As @Sfili_81 mentionned it

    something like word-break: break-all;

    Here you go

    var txt = document.getElementById("demo").innerHTML;
    
    var dataArr = txt.split(' ');
    
    var paragraph = document.getElementById("demo");
    var finalString = "";
    for (var i = 0; i < dataArr.length; i++){
        if (dataArr[i].length > 6 ) {
          finalString = finalString + " <span>"+ dataArr[i]+"</span>"; 
      }
      else{
        finalString = finalString + " " + dataArr[i];
      }
    }
    
    paragraph.innerHTML = finalString;
    div{
      width:50px;
      background: red;
     
    }
    span{
      word-break:break-all;
    }
    <div id="demo">test teeeeeeeeeeest test test test</div>

    PS: I still flagged the question as duplicate from: How to force a line break in a long word in a DIV?

    EDIT

    As break-all is also breaking the whole text / word and break-word is letting a white space / gap before the long word, then it is not adapting. So only solution is JS. In this example, We are injecting span element to text with length over 6.