Last active
October 1, 2021 10:05
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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