Continuous space at the end of the line

Suppose I have a paragraph of text. The first shows what I have for a moment. The second is what I would like to have. So, this is all about words that have 3 or less letters at the end of a line. I want them to be on the verge of the next line.

I could use an indestructible cosmic entity between the words "tempor" and "ex" (etc.), but it looks like a lot of work. Since there is no CSS property for this, I thought the only reasonable way to work it was to use some JS to manage it. This way all the HTML comes from the server without inextricable lines, and then the JS code gets all the text and puts the inextricable space mark in the right places. Are there any ready-to-use libraries to control this? Is this a good way to control this? Will it be effective with huge blocks of text?

enter image description here

+4
source share
2 answers

, \b, 1 - 3- , , .

, ( ).

, :

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&nbsp;</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>
+2

, JS :

$(function() {
    $('p, li').each(function() {
            var text = $(this).html();
            text = text.replace(/(\s)([\S])[\s]+/g,"$1$2&nbsp;"); //one char
            text = text.replace(/(\s)([^<][\S]{1})[\s]+/g,"$1$2&nbsp;"); //two char
            text = text.replace(/(\s)([^<][\S]{1}.)[\s]+/g,"$1$2&nbsp;"); //two char with dot
            $(this).html(text);

        });
});
+1

Source: https://habr.com/ru/post/1651065/


All Articles