From bbc02f6a4798c9f352a6afda47657fb952e1f10d Mon Sep 17 00:00:00 2001 From: gka Date: Mon, 14 Nov 2022 21:02:06 +0100 Subject: [PATCH] feat: escape special markdown characters --- src/index.js | 13 ++++++++++++- test/index.js | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 3938c5c..ab24df9 100644 --- a/src/index.js +++ b/src/index.js @@ -30,6 +30,8 @@ export default function parse(md, prevLinks) { links = prevLinks || {}, last = 0, chunk, prev, token, inner, t; + // escape special characters + md = md.replace(/\\([*_[\]{}`<>()#+\-!|.])/g, m => `&%${m.charCodeAt(1)}%;`); function tag(token) { let desc = TAGS[token[1] || '']; @@ -105,5 +107,14 @@ export default function parse(md, prevLinks) { out += chunk; } - return (out + md.substring(last) + flush()).replace(/^\n+|\n+$/g, ''); + return ( + out + + md + .substring(last) + // unscape special characters + .replace(/&%[0-9]+%;/g, (m) => + String.fromCharCode(+m.substring(2, m.length - 2)) + ) + + flush() + ).replace(/^\n+|\n+$/g, ''); } diff --git a/test/index.js b/test/index.js index 5262b16..8fcac77 100644 --- a/test/index.js +++ b/test/index.js @@ -167,4 +167,21 @@ describe('snarkdown()', () => { expect(snarkdown('`')).to.equal('`'); }); }); + + describe('escaping', () => { + it('should escape special charcters', () => { + expect(snarkdown('\\*foo')).to.equal('*foo'); + expect(snarkdown('this\\*is\\*important')).to.equal('this*is*important'); + expect(snarkdown('\\_foo')).to.equal('_foo'); + expect(snarkdown('\\[foo')).to.equal('[foo'); + expect(snarkdown('\\]foo')).to.equal(']foo'); + expect(snarkdown('\\(foo')).to.equal('(foo'); + expect(snarkdown('\\)foo')).to.equal(')foo'); + expect(snarkdown('\\{foo')).to.equal('{foo'); + expect(snarkdown('\\}foo')).to.equal('}foo'); + expect(snarkdown('\\-foo')).to.equal('-foo'); + expect(snarkdown('\\+foo')).to.equal('+foo'); + expect(snarkdown('\\#foo')).to.equal('#foo'); + }); + }); });