Skip to content

Commit

Permalink
add unescape method
Browse files Browse the repository at this point in the history
  • Loading branch information
tomerlichtash committed Oct 29, 2024
1 parent 7c0be21 commit 16e766d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
7 changes: 7 additions & 0 deletions packages/libs/escape-markdown/src/escapeMarkdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@ export const escapeMarkdown = (s: string) => {
const regexp = new RegExp(`(${escapedTextRegexp})`, 'g');
return s.replace(regexp, '\\$1');
};

export const unescapeMarkdown = (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, (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 16e766d

Please sign in to comment.