Public
Edited
Dec 15
4 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
html`<pre>${escapeHTML(
wordWrap(text, width, indent_two_spaces ? " " : "")
)}</pre>`
Insert cell
function wordWrap(text, width, indent = "") {
const lines = [];
let currentLine = "";

text.split("\n").forEach((line) => {
if (line.trim() === "") {
lines.push(line); // Preserve empty lines with their original whitespace
} else {
const leadingSpace = line.match(/^\s*/)[0]; // Capture leading whitespace
const words = line.trim().split(" ");

currentLine = leadingSpace; // Start the line with original leading whitespace

words.forEach((word) => {
if (currentLine.length + word.length <= width) {
currentLine += (currentLine.trim() ? " " : "") + word;
} else {
lines.push(indent + currentLine);
currentLine = leadingSpace + word; // New line starts with leading whitespace
}
});

if (currentLine.trim()) {
lines.push(indent + currentLine);
}
currentLine = "";
}
});

if (currentLine.trim()) {
lines.push(indent + currentLine);
}

return lines.join("\n");
}
Insert cell
Insert cell
function escapeHTML(str) {
return str.replace(/[&<>"']/g, function (match) {
return {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;"
}[match];
});
}
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