Skip to content

Commit

Permalink
chore: escpapeMarkdown fixes RELEASE (#834)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomerlichtash authored Oct 29, 2024
1 parent 7c0be21 commit 9ce5bac
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
14 changes: 11 additions & 3 deletions packages/libs/escape-markdown/src/escapeMarkdown.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
const mdChars = ['*', '#', '/', '(', ')', '[', ']', '_', '<', '>', '`'];

const createRegexp = (prefix: string) => {
const regex = mdChars.map((char) => `${prefix}${char}`).join('|');
return new RegExp(`(${regex})`, 'g');
};

export const escapeMarkdown = (s: string) => {
if (typeof s !== 'string') return s;
const escapedTextRegexp = mdChars.map((char) => `\\${char}`).join('|');
const regexp = new RegExp(`(${escapedTextRegexp})`, 'g');
return s.replace(regexp, '\\$1');
return s.replace(createRegexp('\\'), '\\$1');
};

export const unescapeMarkdown = (s: string) => {
if (typeof s !== 'string') return s;
return s.replace(createRegexp('\\\\'), (match) => match.slice(1));
};
17 changes: 16 additions & 1 deletion packages/libs/escape-markdown/test/escapeMarkdown.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { escapeMarkdown } from '../src';
import { escapeMarkdown, unescapeMarkdown } from '../src';

describe('escape markdown', () => {
it('should escape markdown chars', () => {
Expand All @@ -11,3 +11,18 @@ describe('escape markdown', () => {
expect(escapeMarkdown(source as any)).toEqual(source);
});
});

describe('unescape markdown', () => {
it('should unescape markdown chars', () => {
const source =
'\\*asterisk\\* \\_underscore\\_ \\(brackets1\\) \\[brackets2\\] \\`backtick\\`';
expect(unescapeMarkdown(source)).toEqual(
'*asterisk* _underscore_ (brackets1) [brackets2] `backtick`',
);
});

it('ignore non-strings', () => {
const source = 1234;
expect(unescapeMarkdown(source as any)).toEqual(source);
});
});

0 comments on commit 9ce5bac

Please sign in to comment.