Skip to content

Commit

Permalink
🐛 fix: Extra Backslash in Code Blocks ($0 -> /$0) (lobehub#177)
Browse files Browse the repository at this point in the history
* Update utils.ts

* fix: Update escapeDollarNumber function to handle code blocks and single line code blocks

* Create utils.test.ts

* Update utils.test.ts
  • Loading branch information
sxjeru authored Jul 8, 2024
1 parent 079bc9a commit f77df56
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 8 deletions.
25 changes: 25 additions & 0 deletions src/Markdown/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { escapeDollarNumber } from './utils';

describe('escapeDollarNumber', () => {
it('should escape dollar signs followed by numbers', () => {
expect(escapeDollarNumber('This costs $10.')).toBe('This costs \\$10.');
expect(escapeDollarNumber('I have $20 and you have $30')).toBe('I have \\$20 and you have \\$30');
});

it('should not escape dollar signs in code blocks', () => {
expect(escapeDollarNumber('```\n$10\n```')).toBe('```\n$10\n```');
expect(escapeDollarNumber('This is a inline code block: `$10`')).toBe('This is a inline code block: `$10`');
});

it('should handle multiple cases', () => {
expect(escapeDollarNumber('This costs $10. But this code is fine: `$10`.')).toBe('This costs \\$10. But this code is fine: `$10`.');
});

it('should handle edge cases', () => {
expect(escapeDollarNumber('')).toBe('');
expect(escapeDollarNumber('$')).toBe('$');
expect(escapeDollarNumber('$$')).toBe('$$');
expect(escapeDollarNumber('$1$2$3')).toBe('\\$1\\$2\\$3'); // 多个需要转义的情况
});
});
39 changes: 31 additions & 8 deletions src/Markdown/utils.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,40 @@
export function escapeDollarNumber(text: string) {
export function escapeDollarNumber(text: string): string {
let escapedText = '';

for (let i = 0; i < text.length; i += 1) {
let inCodeBlock = false;
let inSingleLineCodeBlock = false;
let i = 0;
while (i < text.length) {
let char = text[i];
const nextChar = text[i + 1] || ' ';

if (char === '$' && nextChar >= '0' && nextChar <= '9') {
if (char === '`') {
let tickCount = 1;
while (text[i + tickCount] === '`') {
tickCount++;
}
if (tickCount === 3) {
inCodeBlock = !inCodeBlock;
escapedText += '```';
i += tickCount;
continue;
} else if (tickCount === 1) {
inSingleLineCodeBlock = !inSingleLineCodeBlock;
escapedText += '`';
i += tickCount;
continue;
}
}
if (
!inCodeBlock &&
!inSingleLineCodeBlock &&
char === '$' &&
i + 1 < text.length &&
text[i + 1] >= '0' &&
text[i + 1] <= '9'
) {
char = '\\$';
}

escapedText += char;
i++;
}

return escapedText;
}

Expand Down

0 comments on commit f77df56

Please sign in to comment.