From a739470364eda4c03a3d947bdc80289f1ffbe970 Mon Sep 17 00:00:00 2001 From: underway Date: Wed, 12 Feb 2025 00:34:08 +0800 Subject: [PATCH] Fix the bug where clicking the copy button copies line numbers along with the code when line numbers are enabled in code blocks --- assets/ts/main.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/assets/ts/main.ts b/assets/ts/main.ts index f3160ae..3c28cb7 100644 --- a/assets/ts/main.ts +++ b/assets/ts/main.ts @@ -75,8 +75,18 @@ let Stack = { const codeBlock = highlight.querySelector('code[data-lang]'); if (!codeBlock) return; + const removeLineNumbers = (text: string): string => { + return text.split('\n') + .map(line => { + const lineNumberMatch = line.match(/^\s*\d+[\s.:]?(.*)/); + return lineNumberMatch ? lineNumberMatch[1] : line; + }) + .join('\n'); + }; + copyButton.addEventListener('click', () => { - navigator.clipboard.writeText(codeBlock.textContent) + const processedCode = removeLineNumbers(codeBlock.textContent); + navigator.clipboard.writeText(processedCode) .then(() => { copyButton.textContent = copiedText; @@ -86,7 +96,6 @@ let Stack = { }) .catch(err => { alert(err) - console.log('Something went wrong', err); }); }); });