JSFiddle - React, Tailwind, and code Playground
by emilcieslar
JavaScript
function justify(str = "", limit = 0) {
const spaceAfterWord = 1;
let total = "";
let line = [];
let count = 0;
function combineLine() {
const wordsCount = line.length;
const chartsCount = count - wordsCount;
const spaceCount = limit - chartsCount;
const lastWordIndex = wordsCount - 1;
for (let i = 0; i < spaceCount; i += 1) {
line[wordsCount === 1 ? 0 : i % lastWordIndex] += " ";
}
return line.join("");
}
function addNewLine() {
if (total) {
total += "\n";
}
}
str.split(/\s+/g).forEach(function(word) {
const wordWithSpace = word.length + spaceAfterWord;
const nextCount = count + wordWithSpace;
if (nextCount - spaceAfterWord <= limit) {
line.push(word);
count = nextCount;
} else {
addNewLine();
total += combineLine();
count = wordWithSpace;
line = [word];
}
});
if (line.length > 0) {
addNewLine();
total += combineLine();
}
return total;
}
const str = `Lorem Ipsum is simply dum text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.`;
console.log(justify(str, 25));