Last active
June 30, 2021 20:03
-
-
Save Venryx/84cce3413b1f7ae75b3140dd128f944c to your computer and use it in GitHub Desktop.
String.AsMultiline
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
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