Skip to content

Instantly share code, notes, and snippets.

@cppio
Last active May 11, 2020 20:01
Show Gist options
  • Select an option

  • Save cppio/ea4f1cf38303457f6fe40fc4597a254c to your computer and use it in GitHub Desktop.

Select an option

Save cppio/ea4f1cf38303457f6fe40fc4597a254c to your computer and use it in GitHub Desktop.
A simple JavaScript function/tag function that removes extra levels of indentation. Useful when embedding code in a template literal that is further indented.
const unindent = (template, ...substitutions) => {
const string = String.raw({ raw: template.raw || [template] }, ...substitutions).trimEnd().replace(/^\s*\n/, '');
const indent = (string.match(/^[ \t]*(?=\S)/gm) || []).map(i => i.length).reduce((a, b) => Math.min(a, b));
return string.replace(new RegExp(String.raw`^[ \t]{${indent}}`, 'gm'), '');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment