diff --git a/packages/libs/escape-markdown/src/escapeMarkdown.ts b/packages/libs/escape-markdown/src/escapeMarkdown.ts index c1f0bdf52..be7e46c02 100644 --- a/packages/libs/escape-markdown/src/escapeMarkdown.ts +++ b/packages/libs/escape-markdown/src/escapeMarkdown.ts @@ -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)); }; diff --git a/packages/libs/escape-markdown/test/escapeMarkdown.test.ts b/packages/libs/escape-markdown/test/escapeMarkdown.test.ts index d8a740a4d..af0ed0c6b 100644 --- a/packages/libs/escape-markdown/test/escapeMarkdown.test.ts +++ b/packages/libs/escape-markdown/test/escapeMarkdown.test.ts @@ -1,4 +1,4 @@ -import { escapeMarkdown } from '../src'; +import { escapeMarkdown, unescapeMarkdown } from '../src'; describe('escape markdown', () => { it('should escape markdown chars', () => { @@ -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); + }); +});