From ec5de911235db7084e574da3e8496a8701de13bf Mon Sep 17 00:00:00 2001 From: Bart Enkelaar Date: Mon, 27 Apr 2020 13:56:27 +0200 Subject: [PATCH] Issue 12138 - Fix chat support for regex chars in code blocks --- test/api/unit/libs/highlightMentions.test.js | 14 ++++++++++++++ website/server/libs/highlightMentions.js | 8 +++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/test/api/unit/libs/highlightMentions.test.js b/test/api/unit/libs/highlightMentions.test.js index 678f2d7178..b00c3ed00b 100644 --- a/test/api/unit/libs/highlightMentions.test.js +++ b/test/api/unit/libs/highlightMentions.test.js @@ -119,4 +119,18 @@ describe('highlightMentions', () => { expect(err).to.be.undefined; }); + + it('github issue 12138, method crashes when regex chars are used in code block', async () => { + const text = '`[test]`'; + + let err; + + try { + await highlightMentions(text); + } catch (e) { + err = e; + } + + expect(err).to.be.undefined; + }); }); diff --git a/website/server/libs/highlightMentions.js b/website/server/libs/highlightMentions.js index 9876522060..c2b2281b70 100644 --- a/website/server/libs/highlightMentions.js +++ b/website/server/libs/highlightMentions.js @@ -1,3 +1,4 @@ +import escapeRegExp from 'lodash/escapeRegExp'; import habiticaMarkdown from 'habitica-markdown'; import { model as User } from '../models/user'; @@ -57,14 +58,15 @@ function withOptionalIndentation (content) { } function createCodeBlockRegex ({ content, type, markup }) { + const contentRegex = escapeRegExp(content); let regexStr = ''; if (type === 'code_block') { - regexStr = withOptionalIndentation(content); + regexStr = withOptionalIndentation(contentRegex); } else if (type === 'fence') { - regexStr = `\\s*${markup}.*\n${withOptionalIndentation(content)}\\s*${markup}`; + regexStr = `\\s*${markup}.*\n${withOptionalIndentation(contentRegex)}\\s*${markup}`; } else { // type === code_inline - regexStr = `${markup} ?${content} ?${markup}`; + regexStr = `${markup} ?${contentRegex} ?${markup}`; } return new RegExp(regexStr);