У меня есть блок максимальной шириной 500px, в нем находится определенный текст и в зависимости от разрешения экрана заказчик хочет, чтобы в конце строки никогда не оставалось слова the,a,at, to или например если переноситься 1 слово на следующую строку то он требует что бы я это исправлял, как бы никто так не делает по типографике. Например
Если бы у меня была одна страница то было-бы не сложно сделать хотя бы на full-HD, но у меня дублируется такая страница 5 раз только с разными текстами, и уменьшая один блок, у меня лезит другой текст на другой странице. Помогите объяснить заказчику что это маразм. Другой выход если ему угодить нужно создавать еще кучу доп классов и указывать каждый блок разной длинной, чтобы все слова влазили. Дайте совет как поступать.
let text = $('#source').text();
var textRegex = /((the|to|for|of|by|on) \S+)/gmi;
$('#target').html(text.replace(textRegex, '<nobr>$1</nobr>'));
p {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='source'>Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using
'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.
Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</p>
<p id='target'></p>
var toReplace = ['the', 'to', 'for', 'of', 'by', 'on', 'a', 'an', 'in'];
for (var i = 0; i < toReplace.length; i++) {
while ($('#block').text().indexOf(' ' + toReplace[i] + ' ') != -1) {
$('#block').html($('#block').text().replace(' ' + toReplace[i] + ' ', ' ' + toReplace[i] + ' '));
}
}
#block {
width: 200px;
border: 1px black solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='block'>Where can I get some? There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.</p>
С помощью предыдущих примеров собрал для себя вот такое, только я не понимаю как брать предпоследнее слово с помощью регулярного выражения. Кто знает подскажите.
let toReplace = document.querySelectorAll("p");
let textRegex = /((to the| the| to|for a| for| of| by| on| is| at| a| as| in| an| it) \S+)/gmi;
toReplace.forEach(element => {
element.innerHTML = element.innerText.replace(textRegex, '<nobr>$1</nobr>');
});
p{max-width:520px}
<p class="blockquote">We are<nobr> the first</nobr> and only company that has developed<nobr> an Encrypted</nobr> Calendar. This allows you<nobr> to have</nobr><nobr> a secure</nobr> control over your personal and corporate schedules.</p>
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости