Let's assume I have a paragraph of text. The first one shows what I have at the momment. The second one is what I would like to have. So, it's all about the words that have 3 or less letters at the end of the line. I want them to be at the begenning of the next line.
I could use a non breaking space entity between "tempor" and "ex" words (and so on), but this looks like a lot of job. Since there's no CSS property to handle it, I thought the only reasonable way to work it around is to use some JS to control it. So, all the HTML comes from server without non-breaking lines and then a JS code gets all the text and puts a non-breaking-space sign in the desired places. Are there any ready to use libraries to control it this was? Is this a good way to control it? Is this going to be efficient withing huge blocks of text?
You could use a regular expression using word boundary detection \b
to match 1 to 3-character words followed by a space, then replace the space with a non-breakable one.
However, a potential problem with this approach is that any long sequence of short words becomes non-breakable (as a whole).
Below is some example code with an additional highlighting of the blocks that are modified:
var text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras dictum, mauris eget varius iaculis, lorem dolor luctus ante, sit amet lobortis mauris nibh vitae metus. Quisque imperdiet massa eu consectetur venenatis. Vivamus vitae tortor dolor. Nam ac neque a quam ultrices euismod quis ultricies arcu. Duis feugiat tortor ac enim commodo pharetra. Praesent commodo nisl quis diam consequat molestie. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In a leo in elit accumsan maximus. Mauris vitae egestas eros. Quisque a augue a velit suscipit vehicula quis id dui.';
var formatted = text.replace(/(\b\w{1,3}\b) /g, '<span>$1 </span>');
document.getElementById('output1').innerHTML += text;
document.getElementById('output2').innerHTML += formatted;
p { width:290px; float:left; margin-left:10px; text-align:justify }
span { background-color:#ff8; border: 1px dotted #777 }
<p id="output1"><b>Before:</b><br></p><p id="output2"><b>After:</b><br></p>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments