2023-02-23 23:56:55 -05:00
|
|
|
const regex = /```([^`\n]*?)\n([\s\S]*?)\n```/g;
|
|
|
|
|
|
2023-02-25 10:16:21 -05:00
|
|
|
const unenclosedCodeTest = (text) => {
|
|
|
|
|
let workingText = text;
|
|
|
|
|
if (workingText.startsWith('<') || (!workingText.startsWith('`') && workingText.match(/```/g)?.length === 1)) {
|
|
|
|
|
workingText = `\`\`\`${workingText}`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return workingText;
|
|
|
|
|
};
|
|
|
|
|
|
2023-02-23 23:56:55 -05:00
|
|
|
export default function regexSplit(string) {
|
|
|
|
|
const matches = [...string.matchAll(regex)];
|
|
|
|
|
const output = [matches[0].input.slice(0, matches[0].index)];
|
|
|
|
|
|
2023-02-25 10:16:21 -05:00
|
|
|
// console.log(matches);
|
|
|
|
|
|
2023-02-23 23:56:55 -05:00
|
|
|
for (let i = 0; i < matches.length; i++) {
|
|
|
|
|
const [fullMatch, language, code] = matches[i];
|
|
|
|
|
// const formattedCode = code.replace(/`+/g, '\\`');
|
2023-02-24 11:24:09 -05:00
|
|
|
output.push(`\`\`\`${language}\n${code}\n\`\`\``);
|
2023-02-23 23:56:55 -05:00
|
|
|
if (i < matches.length - 1) {
|
2023-02-25 10:16:21 -05:00
|
|
|
let nextText = string.slice(matches[i].index + fullMatch.length, matches[i + 1].index);
|
|
|
|
|
nextText = unenclosedCodeTest(nextText);
|
|
|
|
|
output.push(nextText);
|
|
|
|
|
} else {
|
|
|
|
|
const lastMatch = matches[matches.length - 1][0];
|
|
|
|
|
// console.log(lastMatch);
|
|
|
|
|
// console.log(matches[0].input.split(lastMatch));
|
|
|
|
|
let rest = matches[0].input.split(lastMatch)[1]
|
|
|
|
|
|
|
|
|
|
if (rest) {
|
|
|
|
|
rest = unenclosedCodeTest(rest);
|
|
|
|
|
output.push(rest);
|
|
|
|
|
}
|
2023-02-23 23:56:55 -05:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-02-25 10:16:21 -05:00
|
|
|
console.log(output);
|
|
|
|
|
|
|
|
|
|
// for (let i = 0; i < matches.length; i++) {
|
|
|
|
|
// const [fullMatch, language, code] = matches[i];
|
|
|
|
|
// output.push(`\`\`\`${language}\n${code}\n\`\`\``);
|
|
|
|
|
// if (i < matches.length - 1 && matches[i + 1]) {
|
|
|
|
|
// const nextText = string.slice(matches[i].index + fullMatch.length, matches[i + 1].index);
|
|
|
|
|
// output.push(nextText.trim());
|
|
|
|
|
// } else if (i === matches.length - 1) {
|
|
|
|
|
// const nextText = string.slice(matches[i].index + fullMatch.length);
|
|
|
|
|
// output.push(nextText.trim());
|
|
|
|
|
// }
|
|
|
|
|
// }
|
|
|
|
|
|
|
|
|
|
// console.log(output);
|
|
|
|
|
|
2023-02-23 23:56:55 -05:00
|
|
|
return output;
|
|
|
|
|
}
|