Last active
June 24, 2023 12:00
-
-
Save DeityLamb/02bf3dcae1855ee2ff5491a6f493d2b4 to your computer and use it in GitHub Desktop.
Split a markdown without breaking a code block
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
function splitMarkdown(str: string, limit: number): string[] { | |
return str.match(new RegExp(`.*([^]){1,${limit}}(\n)?$`, 'gm')).reduce((acc, curr) => { | |
const lastValue = acc.at(-1); | |
if (!lastValue) return [curr]; | |
const heads = lastValue.match(/```.*/g) as string[] || []; | |
// If the number of heads is even or 0, then all code blocks are closed | |
const isCodeBlockClosed = (heads.length % 2 === 0) || !heads.length; | |
return [ | |
// We are updating the last value, so we slice the accumulator | |
...acc.slice(0, -1), | |
// If the code block is not closed, then close it | |
isCodeBlockClosed ? lastValue : lastValue + '\n```', | |
// And open it with the same last open head | |
isCodeBlockClosed ? curr : heads.at(-1) + '\n' + curr | |
]; | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment