Skip to content

Instantly share code, notes, and snippets.

@benbenbenbenbenben
Last active October 1, 2021 10:05
Show Gist options
  • Save benbenbenbenbenben/e6a93348c0bbbbb43f2b796c8ca7b67a to your computer and use it in GitHub Desktop.
Save benbenbenbenbenben/e6a93348c0bbbbb43f2b796c8ca7b67a to your computer and use it in GitHub Desktop.
trim whitespace from start and end of lines in multiline strings in js/ts
// This little function joins strings[0] with the l-r-... zip of strings.slice(1) and expr
// TypeScript
export const linetrim = (strings: TemplateStringsArray, ...expr: string[]): string => {
return strings.slice(1).reduce((str, fragment, i) => str + expr[i] + fragment, strings[0]).replace(/^.*$/gm, line => line.trim() + `\n`)
}
// JavaScript
export const linetrim = (strings, ...expr) => {
return strings.slice(1).reduce((str, fragment, i) => str + expr[i] + fragment, strings[0]).replace(/^.*$/gm, line => line.trim() + `\n`)
}
// Usage
const a = linetrim`this
is
a
multiline
string`
const b = linetrim`this
is
a
multiline
string`
expect(a).toBe(b) // passes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment