Skip to content

Instantly share code, notes, and snippets.

@jimschubert
Created December 15, 2015 12:23
Show Gist options
  • Save jimschubert/06fea56a6d2a1e7fdbc2 to your computer and use it in GitHub Desktop.
Save jimschubert/06fea56a6d2a1e7fdbc2 to your computer and use it in GitHub Desktop.
ES6/ES2015 tag function to support "indented" strings like Scala's stripMargin function.
/**
* Allows Scala-like stripMargin
*
* Parameters are applied implicitly via ES2015.
*
* @example
* // returns "The Number is:\n 100\nThanks for playing!"
* let num = 100
* let result = stripMargin`The Number is:
* | ${num}
* |Thanks for playing!`
*
*/
export function stripMargin(template, ...expressions) {
let result = template.reduce((accumulator, part, i) => {
return accumulator + expressions[i - 1] + part
})
return result.replace(/\r?(\n)\s*\|/g, '$1');
}
@jimschubert
Copy link
Author

@ygormutti
Copy link

ygormutti commented May 16, 2018

Thanks! Here's a TypeScript, Mac/Windows EOL compatible, linted version:

function stripMargin(template: TemplateStringsArray, ...expressions: any[]) {
    const result = template.reduce((accumulator, part, i) => {
        return accumulator + expressions[i - 1] + part;
    });

    return result.replace(/(\n|\r|\r\n)\s*\|/g, '$1');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment