Я пытаюсь равномерно сбалансировать текст по нескольким строкам , используя только JavaScript и не заботясь о сложности размеров шрифта.
При заданной входной строке и максимальном 1 количество символов в каждой строке, как я могу равномерно сбалансировать 2 текст над минимальным количеством строк?
Я использую актуальную версию Google Chrome и поддержка устаревших браузеров не важна для моего вопроса.
Ниже приведена моя попытка без попытки сбалансировать текст (что я хочу, но я не знаю, как go сделать это).
Возможно удалить один или оба метода replace()
, изменив строку RegExp в методе match()
.
const stringInputsAndExpectedArrayOutputs = [
['', ['']],
[' ', ['']],
[' ', ['']],
['.', ['.']],
['The ', ['The']],
['The quick\nbrown fox', ['The quick brown', 'fox']],
['Thequickbrownfox jumpsoverthelazydog.', ['Thequickbrownfox', 'jumpsoverthelazydog.']],
[' The quick brown fox jumps over the lazy dog. ', ['The quick brown', 'fox jumps over', 'the lazy dog.']],
['The quick brown fox jumps over the lazy dog.', ['The quick brown', 'fox jumps over', 'the lazy dog.']]
];
const maximumCharactersPerLine = 15;
const distributeTextOverLines = ((stringInput, maximumCharactersPerLine) => {
let arrayOutput = stringInput.replace(/[\r\n ]+$/g, '').replace(/[\r\n ]{2,}|[\r\n]/g, ' ');
arrayOutput = arrayOutput.match(new RegExp(`(?! )(?:.{1,${maximumCharactersPerLine}}|[^ ]+)(?= |$)`, 'g')) || [''];
return arrayOutput;
});
for (const [stringInput, expectedArrayOutput] of stringInputsAndExpectedArrayOutputs) {
const arrayOutput = distributeTextOverLines(stringInput, maximumCharactersPerLine);
const arrayOutputDifferentThanExpected = !(arrayOutput.length === expectedArrayOutput.length && arrayOutput.every((value, index) => value === expectedArrayOutput[index]));
if (arrayOutputDifferentThanExpected) {
console.log('array output:');
console.log(arrayOutput);
console.log('expected array output:');
console.log(expectedArrayOutput);
continue;
}
const stringOutput = arrayOutput.join('\n');
console.log('string output:');
console.log(stringOutput);
}
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
1 Если слово длиннее максимального предела, тогда строка должна содержать целое слово, переполняющее его.
2 Распределите текст таким образом, чтобы в каждой строке было столько же символов, сколько и в других, что делает ширину всех строк вместе как можно меньше.