Skip to content

Instantly share code, notes, and snippets.

@Venryx
Last active June 30, 2021 20:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Venryx/84cce3413b1f7ae75b3140dd128f944c to your computer and use it in GitHub Desktop.
Save Venryx/84cce3413b1f7ae75b3140dd128f944c to your computer and use it in GitHub Desktop.
String.AsMultiline
declare global {
interface String {
/**
* Reformats a multi-line string to represent the actual intended "block" of text.
* @param desiredIndent How much to indent each line. (after removal of the first-line indent-length from each of them)
*/
AsMultiline(desiredIndent: number): string;
}
}
String.prototype.AsMultiline = function(this: string, desiredIndent: number = null) {
let result = this.substring(this.indexOf("\n") + 1, this.lastIndexOf("\n"));
if (desiredIndent != null) {
let lines = result.split("\n");
let firstLineIndent = result.match(/^(\t+)/)?.[1].length ?? 0;
if (firstLineIndent) {
// remove X tabs from start of each line (where X is firstLineIndent)
lines = lines.map(line=>line.replace(new RegExp(`^\t{0,${firstLineIndent}}`), ""));
}
// add the desired indent
lines = lines.map(line=>"\t".repeat(desiredIndent) + line);
result = lines.join("\n");
}
return result;
};
// usage example
// ==========
return (
<Text>{`
This is the first line.
This is the second line.
The resulting string will not contain any indent, since it's passed through the AsMultiline post-processor.
`.AsMultiline(0)}</Text>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment