dedent Strips Common Leading Indent
Strip the smallest common leading indent from multi-line template text so nested call sites still produce flush, presentable output.
Code
// Multi-line template literals keep the source indentation of the
// call site. dedent splices values back in, finds the smallest
// leading indent across non-blank lines, and strips it everywhere.
function dedent(strings, ...values) {
let text = '';
strings.forEach((chunk, i) => {
text += chunk;
if (i < values.length) text += values[i];
});
const lines = text.replace(/^\n/, '').split('\n');
const indents = lines
.filter((line) => line.trim().length > 0)
.map((line) => line.match(/^[ \t]*/)[0].length);
const pad = Math.min(...indents);
return lines.map((line) => line.slice(pad)).join('\n').trimEnd();
}
function renderBanner(name) {
return dedent`
*** deploy report ***
service: ${name}
status: ready
`;
}
console.log(renderBanner('billing'));How dedent measures the indent
dedent(strings, ...values) is a template-literal tag. It first splices each values[i] between the raw chunks (if (i < values.length) text += values[i]), drops one leading newline with text.replace(/^\n/, ''), and splits the rest into lines. Only non-blank lines contribute to the measurement — .filter((line) => line.trim().length > 0) — each contributing its leading space/tab count from line.match(/^[ \t]*/)[0].length. Math.min(...indents) picks the smallest, and lines.map((line) => line.slice(pad)) strips exactly that many columns from every line, including blanks where the slice is harmless.
What renderBanner produces
renderBanner('billing') feeds a two-space-indented template through the tag, so the printed block comes out flush left instead of carrying the call site’s indentation:
*** deploy report ***
service: billing
status: ready
The strip in one expression
return lines.map((line) => line.slice(pad)).join('\n').trimEnd();
.trimEnd() only removes trailing whitespace at the very end of the joined text, so interior blank lines survive as empty lines — the indent decision is made once, from the non-blank lines, and applied uniformly.
Interactive Tools for This Topic
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `dedent`, `renderBanner` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.