JSFiddle - React, Tailwind, and code Playground
by Evan Sharp
JavaScript
const str = 'Lorem ipsum a dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
const width = 25;
function justify(str, width) {
const words = str.split(/\s+/);
const lines = [];
words.forEach((word, i) => {
const current = lines[lines.length - 1] || '';
const proposed = `${current} ${word}`;
if (i && proposed.length <= width) {
lines[lines.length - 1] = proposed;
} else {
lines.push(word);
}
})
return lines.map(line => {
if (line.length === width) return line;
let newLine = line;
const spacesNeeded = width - line.length;
const spaces = line.split(/\s+/).length - 1;
const spacesPerSpace = Math.floor(spacesNeeded / spaces);
if (spaces) {
let remainder = spacesNeeded % spaces;
const spacesToAdd = spacesPerSpace ? new Array(spacesPerSpace + 1).fill(' ').join('') : ' ';
newLine = line.replace(/\s+/g, match => remainder-- > 0 ? `${spacesToAdd} ` : spacesToAdd);
}
return newLine;
}).join('\n');
}
console.log(justify(str, width));