Skip to content

Instantly share code, notes, and snippets.

@DeityLamb
Last active June 24, 2023 12:00
Show Gist options
  • Save DeityLamb/02bf3dcae1855ee2ff5491a6f493d2b4 to your computer and use it in GitHub Desktop.
Save DeityLamb/02bf3dcae1855ee2ff5491a6f493d2b4 to your computer and use it in GitHub Desktop.
Split a markdown without breaking a code block
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