From 215b259095dd8934f1b8ec03cba3f6c63ad56038 Mon Sep 17 00:00:00 2001 From: naive231 Date: Fri, 15 Nov 2024 10:37:41 +0800 Subject: [PATCH] [fix] Fix the wrong logic that always do the replacement toward the whole text instead the rest part of the text. --- main.ts | 65 +++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 49 insertions(+), 16 deletions(-) diff --git a/main.ts b/main.ts index 7546952..f3ec69b 100644 --- a/main.ts +++ b/main.ts @@ -147,21 +147,54 @@ function processLineBlock(source: string): string { } function applyFormatting(text: string): string { - if (text.includes('**')) { - // Replace **bold** with *bold* (with spaces) - text = text.replace(/\*\*(.*?)\*\*/g, ' *$1* '); - } else if (text.includes('*')) { - // Replace *italic* with _italic_ - text = text.replace(/(? 0) { + let earliestMatch: { pattern: any; match: RegExpExecArray; index: number } | null = null; + let earliestIndex = remainingText.length; + + // Find the earliest match among the patterns + for (let pattern of patterns) { + pattern.regex.lastIndex = 0; // Reset regex index + let match = pattern.regex.exec(remainingText); + if (match && match.index < earliestIndex) { + earliestMatch = { + pattern: pattern, + match: match, + index: match.index, + }; + earliestIndex = match.index; + } + } + + if (earliestMatch) { + // Append text before the match + result += remainingText.slice(0, earliestMatch.index); + + // Apply the replacement + let replacedText = earliestMatch.match[0].replace(earliestMatch.pattern.regex, earliestMatch.pattern.replacement); + + result += replacedText; + + // Update remainingText + remainingText = remainingText.slice(earliestMatch.index + earliestMatch.match[0].length); + } else { + // No more matches, append the rest of the text + result += remainingText; + break; + } } - // Replace ~~strike~~ with ~strike~ - text = text.replace(/~~(.*?)~~/g, ' ~$1~ '); - if (text.includes('==')) { - // Replace ==emphasize== with `emphasize` - text = text.replace(/==(.*?)==/g, ' `$1` '); - } else if (text.includes('`')) { - // Replace `quote` with {quote} - text = text.replace(/`(.*?)`/g, ' {$1} '); - } - return text; + + return result; } +