Public
Edited
Aug 7, 2023
Insert cell
Insert cell
function splitIntoEvenChunks(str, noOfLines = 2) {
let len = str.length;
let wordLen = Math.floor(len / noOfLines);

const lines = [];
let temp = '';
let counter = 0;

const parts = str
.split(' ')
.map((v) => {
return v.length > wordLen ? splitAtShy(v) : v;
})
.flat();

parts.forEach((v, i) => {
wordLen = Math.floor((len - lines.join(' ').length) / (noOfLines - counter));

if ((temp + v).length <= wordLen || i === 0) {
temp += ' ' + v;
} else {
lines.push(temp.trim());
counter++;
temp = v;
}
});

temp.trim() && lines.push(temp.trim());
return lines;
}
Insert cell
function splitAtShy(str) {
const parts = str.split('&shy;');
return parts.map((v, i) => (i < parts.length - 1 && parts.length !== 1 ? `${v}-` : v));
}
Insert cell
splitIntoEvenChunks('Wildfires', 2);
Insert cell
splitIntoEvenChunks('Crop failures', 5);
Insert cell
splitIntoEvenChunks('Tropical cyclones', 2);
Insert cell
splitIntoEvenChunks('Oh oh', 2);
Insert cell
Insert cell
splitIntoEvenChunks('SuchALongWord', 2);
Insert cell
splitIntoEvenChunks('SuchA&shy;LongWord', 2);
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more